Reputation:
In c++17 you can do the following:
if ( init-statement(optional); condition )
according to https://en.cppreference.com/w/cpp/language/if
However my compiler (vs2019) allows
if ( init-statement )
where the init-statement is also the condition. I can't find that this is documented anywhere, is this actually guaranteed to work?
Upvotes: 6
Views: 3502
Reputation: 473312
In C++, a lot of things can go into condition
that you wouldn't expect to be allowed there. A condition
for example can be int i = 20
. int i = 20
resolves to a value which can be contextually converted into a boolean and tested.
So it's not that your compiler is allowing an init-statement
without a condition
. It's that C++ since the beginning has allowed condition
grammar to include declaring a variable, and your code is simply using that.
Upvotes: 12
Reputation: 374
if
statement does:
condition
condition
's return value is true
(contextually convertible to bool) - it executes
{ ... }
condition
's return value is false
- it skips { ... }
So in your case, the if
simply executes init-statement
, and it's return value is not false
so it executes the rest of your code ({ ... }
).
Upvotes: 0