Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 672
Pankaj Prakash Avatar asked Dec 15 '22 13:12

Pankaj Prakash


1 Answers

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

like image 59
nneonneo Avatar answered Jan 01 '23 21:01

nneonneo