4

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?

Varun Garg
  • 2,464
  • 23
  • 37
Pankaj Prakash
  • 2,300
  • 30
  • 31

3 Answers3

5

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

nneonneo
  • 171,345
  • 36
  • 312
  • 383
4
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.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
3

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294