简体   繁体   中英

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

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?

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

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.

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.

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