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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With