Sanish
Sanish

Reputation: 1719

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

Upvotes: 1

Views: 229

Answers (4)

user677656
user677656

Reputation:

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 .

Upvotes: 0

James Kanze
James Kanze

Reputation: 153919

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

Upvotes: 1

Yochai Timmer
Yochai Timmer

Reputation: 49251

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

Upvotes: 1

Mankarse
Mankarse

Reputation: 40603

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.

Upvotes: 11

Related Questions