Variable Declaration in if Expression in C
In C , the syntax for variable declaration within an if expression's condition is often limited. The question arises whether such limitations are standard-based or compiler-specific.
The 2003 C standard (6.4.3) allows variable declarations within an if condition, with scope extending to the controlled substatements. However, it does not explicitly prohibit parentheses around the declaration or multiple declarations within the condition.
Earlier versions of C behaved inconsistently regarding parentheses and multiple declarations. In the provided code samples:
This limitation is inconvenient for scenarios where only one declaration is required within the condition.
C 17 Solution
C 17 introduced a solution to this problem:
if (int a = Func1(), b = Func2(); a && b) { // Do stuff with a and b. }
This syntax utilizes a semicolon (;) to separate the declaration from the condition. It allows for multiple variable declarations within a single condition, eliminating the previous inconvenience.
The above is the detailed content of Can C \'s `if` Expression Handle Variable Declarations Consistently Across Standards and Compilers?. For more information, please follow other related articles on the PHP Chinese website!