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

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

    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.

提交回复
热议问题