简体   繁体   中英

How following code compiles in C/C++?

The following code prints -10

int x = 10;
-x;
cout << -x << endl;  // printf("%d\n", -x); 

both in C and C++ compilers (gcc 4.1.2) . I was expecting a compiler error for the second line. May be it is something fundamental, but I do not understand the behavior. Could someone please explain?

Thanks

Statements can be expressions. Such statements discard result of the expression, and evaluate the expression for its side effects.

-x; computes the negation of x and discards the result.

For more information read [stmt.expr] in the C++ standard.

When you do -x; the operator - is preformed on the variable.
The operator returns the value of the negation, but doesn't change the object itself.

So because you don't store the result of the operator, x itself still has the same value.

When you print the -x to the cout , you see the result of the operator - which is returned to the operator <<

C++ doesn't have an assignment statement, or a procedure call statement. It defines assignment as an operator in an expression, with side effects, and has an expression statement. It is expected that the top level operator in an expression statement have side effects—that it either modify state, like an assignment operator, or it calls a function. But the language doesn't require it, and expression statements with no side effects whatever are perfectly legal.

A good compiler will output a warning in such cases, since it's almost certainly a programmer error (and you can usually shut up the warning by explicitly casting the results to void , if for some reason you want such a statement—the assert macro often does this).

Second line has not effect on x but is computed. Third has no effect on x but the computed output is sent to standard output std::cout . To make things a bit simpler to understand:

int x=10;
std::cout << x-10 << std::endl;
std::cout << x << std::endl; 

will output 0 and 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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