How does `int sum = n + - + - + - + n` compile where `n` is an `int`?

143 views Asked by At

This afternoon, I really don't know what I was doing with Operators and C. Eventually, I wrote some code which I was thinking wouldn't compile, But I don't know how it worked.

The code is:

#include <stdio.h>

int main()
{
    int n=2;
    int sum = n + - + - + - + n;  /* This line */
    printf("%d\n", sum);
    return 0;
}

And the output is:

0

I am completely confused how the code compiled and what is happening behind the scene.

How does the line int sum = n + - + - + - + n; work?

3

There are 3 answers

0
Mohit Jain On BEST ANSWER
int sum = n + - + - + - + n;
/*          b u u u u u u   */
/* Order:   7 6 5 4 3 2 1   */

is equivalent to:

n + (-(+(-(+(-(+n))))));

or simply n + (-n)

Note that unary operators bind more tightly than binary operators in C opeartor precedance table and associativity of unary operator +- is from right to left while of binary +- operators in from left to right.

8
nneonneo On

All but the first are just unary operators.

n + - + - + - + n

is equivalent to

n + (-(+(-(+(-(+n))))))

which is in turn simply equal to

n + (-n)

after resolving all the unary operators.

-n is, of course, ordinary negation; +n does essentially nothing (though it has the side effect of forcing integral promotion).

0
Yu Hao On

Both of + and - are also unary operators. The result of +n is the (promoted) value of n. The result of -n is the negative of (promoted) n.

n + - + - + - + n;

is equivalent to:

n + (-(+(-(+(-(+n))))))

which is basically n + (-n) assuming no overflow happens.