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

后端 未结 4 2045
悲&欢浪女
悲&欢浪女 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:33

    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

提交回复
热议问题