Home > Backend Development > C++ > Can C 17 Declare Variables Inside an \'if\' Condition?

Can C 17 Declare Variables Inside an \'if\' Condition?

Linda Hamilton
Release: 2024-12-02 09:15:13
Original
741 people have browsed it

Can C  17 Declare Variables Inside an 'if' Condition?

C Variable Declaration in 'if' Expression: Resolved in C 17

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
{

}
Copy after login

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.
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template