SIMEL
SIMEL

Reputation: 8941

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).

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?

Upvotes: 4

Views: 179

Answers (2)

P.W
P.W

Reputation: 26800

  • (444); is a statement consisting of a parenthesized expression (444) and a statement terminator ;

  • (444) consists of parentheses () and a prvalue expression 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.

So in this particular case, parentheses have no additional significance, so (444); becomes 444; which is then optimized out by the compiler.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

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 ;.

Of course, any sane compiler operating in accordance with the as-if rule, will remove it during compilation.

One place where at least one statement is required is in a switch block (even if program control never reaches that point):

switch (1){
case 0:
    ; // Removing this statement causes a compilation error
}

Upvotes: 7

Related Questions