Home >Backend Development >C++ >How Has C 17 Changed the Rules for Variable Declaration in `if` Expressions?
Variable Declaration in 'if' Expression: Clarifying the Rules
Variables declared within an 'if' expression condition have been a question mark for programmers for some time. The C standard initially outlined the scope of these variables, but there remained ambiguities regarding parentheses and multiple declarations.
In the provided example, the compiler fails to compile when parentheses are used around the variable declaration:
if((int a = Func1())) { // Fails to compile. }
This behavior, which also extends to cases with multiple declarations in a single condition, is due to the rule that the declaration must immediately precede the condition itself. Parentheses break this rule.
However, with the introduction of C 17, the situation has changed:
if (int a = Func1(), b = Func2(); a && b) { // Do stuff with a and b. }
Now, it is possible to declare variables within brackets, using ; to separate the declaration from the condition. This enhancement expands the flexibility of 'if' conditions.
The above is the detailed content of How Has C 17 Changed the Rules for Variable Declaration in `if` Expressions?. For more information, please follow other related articles on the PHP Chinese website!