简体   繁体   English

括号运算符在C ++中自己做了什么

[英]What does the parenthesis operator does on its own in C++

During writing some code I had a typo that lead to unexpected compilation results and caused me to play and test what would be acceptable by the compiler (VS 2010). 在编写一些代码时,我有一个拼写错误导致意外的编译结果,并导致我玩和测试编译器可以接受的内容(VS 2010)。

I wrote an expression consisting of only the parenthesis operator with a number in it (empty parenthesis give a compilation error): 我写了一个只包含括号运算符的表达式,其中包含一个数字(空括号表示编译错误):

(444);

When I ran the code in debug mode, it seems that the line is simply skipped by the program. 当我在调试模式下运行代码时,程序似乎只是跳过该行。 What is the meaning of the parenthesis operator when it appears by itself? 当括号运算符单独出现时,它的含义是什么?

If I can answer informally, 如果我能非正式地回答,

(444);

is a statement . 是一份声明 It can be written wherever the language allows you to write a statement, such as in a function. 它可以在语言允许您编写语句的任何地方编写,例如在函数中。 It consists of an expression 444 , enclosed in parentheses (which is also an expression) followed by the statement terminator ; 它由一个表达式 444 ,括在括号中(也是一个表达式),后跟语句终止符; .

Of course, any sane compiler operating in accordance with the as-if rule, will remove it during compilation. 当然,任何按照as-if规则运行的理智编译器都会在编译期间将其删除。

One place where at least one statement is required is in a switch block (even if program control never reaches that point): 需要至少一个语句的地方是switch块(即使程序控制永远不会到达该点):

switch (1){
case 0:
    ; // Removing this statement causes a compilation error
}
  • (444); is a statement consisting of a parenthesized expression (444) and a statement terminator ; 是一个由括号表达式(444)和语句终止符组成的语句;

  • (444) consists of parentheses () and a prvalue expression 444 (444)由括号()prvalue表达式444

A parenthesized expression (E) is a primary expression whose type, value, and value category are identical to those of E. The parenthesized expression can be used in exactly the same contexts as those where E can be used, and with the same meaning , except as otherwise indicated. 带括号的表达式(E)是一个主要表达式,其类型,值和值类别与E的类型,值和值类别相同。带括号的表达式可以在与可以使用E的情境完全相同的上下文中使用,具有相同的含义 ,除非另有说明。

So in this particular case, parentheses have no additional significance, so (444); 所以在这种特殊情况下,括号没有其他意义,所以(444); becomes 444 ; 变成444 ; which is then optimized out by the compiler. 然后由编译器优化。

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

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