Home >Backend Development >C++ >How Has C 17 Changed the Rules for Variable Declaration in `if` Expressions?

How Has C 17 Changed the Rules for Variable Declaration in `if` Expressions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 16:30:13616browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn