In C , variable declarations within "if" statement conditions have been a subject of confusion and compiler limitations. Code snippets like the following often raise questions:
if (int a = Func1()) { ... } // Works if ((int a = Func1())) { ... } // Fails to compile if ((int a = Func1()) && (int b = Func2())) { ... } // Works
The C 03 standard allows variable declarations in "if" conditions, with scope extending to the end of the substatements controlled by the condition. However, it doesn't specify restrictions on parentheses or multiple declarations.
Despite the standard's silent allowance, many compilers, including VS2008, enforce limitations:
This limitation can be particularly annoying when declaring multiple variables within a condition and assigning specific values to them. Consider:
bool a = false, b = true; if (bool x = a || b) { ... }
To enter the "if" body with x set to false, parentheses are required around the declaration. However, since parentheses are disallowed, x must be declared outside the body, leaking it to a wider scope.
Before C 17, the desired syntax for multiple variable declarations in "if" conditions was not conformant to the standard. However, compilers often imposed further limitations.
Thankfully, C 17 introduced a new syntax that resolves this issue:
if (int a = Func1(), b = Func2(); a && b) { ... }
In C 17, you can now use a semicolon to separate the declaration from the actual condition, allowing for multiple variable declarations and parentheses.
The above is the detailed content of Can C \'s \'if\' Statement Handle Multiple Variable Declarations?. For more information, please follow other related articles on the PHP Chinese website!