user2039981
user2039981

Reputation:

C++17 if statement with initializer but no condition

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

Answers (2)

Nicol Bolas
Nicol Bolas

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

Gaben
Gaben

Reputation: 374

if statement does:

  • evaluates the output of condition
  • if condition's return value is true (contextually convertible to bool) - it executes { ... }
  • if 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

Related Questions