Can a variable be defined only in the scope of an if-statement, similar to how it's often done for for-loops?

﹥>﹥吖頭↗ 提交于 2019-11-29 15:00:28

As far as I can tell there is no way to have both a declaration and an expression within the condition of an if statement. If we look at the draft C++ standard section 6.4 Selection statements the grammar for if is as follows:

selection-statement:
    if ( condition ) statement
    if ( condition ) statement else statement
    switch ( condition ) statement
condition:
    expression
    attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
    attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

So you either can use an expression or a declaration and I don't see any obvious ways around that.

What you proposed in the alternative, declaring i before the if statement seems like the best option. Although using an enclosing block does not seem necessary:

int i = f();
if(i == 3)

You can declare the variable in the if, but if you do so, the condition depends on the implicit conversion of the type to bool, which is very limiting and a bit obfuscating. The definition in the for works because the first part of the for isn't part of the condition. Just write:

int i = f();
if ( i == 3 ) {
    //  ...
} else {
    //  ...
}

This leaves the variable in scope until the end of the enclosing block, but the enclosing block can't be bigger than the entire function; if leaving it in scope is a problem, then your functions are too large and complex, and need to be refactored.

You can only do a declaration OR boolean logic in an if statement. The C++ spec says so somewhere, forgot where exactly. Therefore a code like: if (int x = 3 && x == 3) {} will never compile because it will also throw the error that x is used uninitialized

The first snippet works because you are declaring and defining i in if's conditional expression. It will always evaluated to true.
The second snippet does not compile because you are comparing a non-primary (because i is declared and defined here) expression in conditional expression with a primary expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!