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

后端 未结 4 2048
悲&欢浪女
悲&欢浪女 2020-12-21 06:13

Is there a way to declare, assign and compare a variable to an expression in an if construction in such a way that it is only defined in the scope of the if construction?

4条回答
  •  悲哀的现实
    2020-12-21 06:53

    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)
    

提交回复
热议问题