简体   繁体   English

Init-Statment 条件表达式 C++

[英]Init-Statment Conditional Expression C++

Can someone please explain to me initializations in if-statements?有人可以向我解释 if 语句中的初始化吗?

This question here is almost the same as mine C++17 if statement with initializer but no condition but I don't feel the responses there were adequate.这里的这个问题与我的C++17 if 语句几乎相同但没有条件但我觉得那里的响应不够。

Why does this work?为什么这行得通?

if( int x = 4 ){ 
  std::cout << x;
}

I was under the impression that initialization does not return a value.我的印象是初始化不返回值。 Indeed the code below is an error:事实上,下面的代码是一个错误:

std::cout << ( int y = 7 );

Quoting from the Standard N4380, the syntax should be:引用标准 N4380,语法应该是:

"if constexpr_opt ( init-statement_opt condition ) statement" “if constexpr_opt (init-statement_opt 条件) 语句”

And quoting further along:并进一步引用:

"An if statement of the form if constexpr_opt ( init-statement condition ) statement is equivalent to " if constexpr_opt (init-statement condition) 语句形式的 if 语句等价于

{ init-statement if constexpr_opt ( condition ) statement }" { init-statement if constexpr_opt ( 条件 ) 语句 }"

And also:并且:

"[Note: An init-statement ends with a semicolon. —end note]" “[注意:初始化语句以分号结尾。-结束注释]”

I can imagine the "int x=4" is the init-statement.我可以想象“int x = 4”是初始化语句。 But

  • then the condition statement, in the example I gave, is missing and the condition statement is not marked as optional那么在我给出的示例中,条件语句丢失并且条件语句标记为可选
  • and the init-statement does not end in a semicolon .并且 init 语句不以分号结尾

EDITED : removed an incorrect statement.编辑:删除了不正确的陈述。

This is not new C++17 syntax.这不是新的 C++17 语法。 It has always been there.它一直都在那里。

int x = 4 in your first example is not the init-statement , but the condition in the grammar rule you quoted.第一个示例中的int x = 4不是init-statement ,而是您引用的语法规则中的条件

condition can be either an expression or a declaration with initializer (and a few other restrictions).条件可以是表达式或带有初始化程序的声明(以及一些其他限制)。 If it has the latter form, then the declaration introduces the declared variable in the branches of the if and the first branch is chosen if the declared variable, contextually converted to bool , yields true after its initialization.如果它具有后一种形式,则声明在if的分支中引入声明的变量,如果声明的变量在上下文中转换为bool ,在其初始化后产生true ,则选择第一个分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM