In C , declaring variables within an 'if' statement's condition expression has been a long-standing limitation. As of C 17, this restriction has been lifted.
Previously, variables declared in an 'if' condition were scoped to the 'if' statement's substatements. Enclosing the declaration in parentheses was prohibited, and only a single declaration was allowed per condition. This limitation was inconvenient in cases where variable initialization within the condition was necessary.
Consider the code snippet:
bool a = false, b = true; if (bool x = a || b) // Cannot declare x within the condition { }
To initialize x to false within the 'if' scope, parentheses were required due to operator precedence. However, parentheses were not permitted, requiring x to be declared outside the 'if'. This leaked the declaration to a wider scope.
In C 17, this constraint has been relaxed. The following code is now valid:
if (int a = Func1(), b = Func2(); a && b) { // Do stuff with a and b. }
Note the use of ";" to separate the declaration from the condition. This allows for multiple declarations and the use of parentheses where appropriate.
Hence, what was previously non-conformant is now possible with the introduction of C 17.
The above is the detailed content of Can C 17 Declare Variables Inside an \'if\' Condition?. For more information, please follow other related articles on the PHP Chinese website!