简体   繁体   中英

Output of program does not make sense

I don't understand the logic behind this..
I expect this program to output 2 but it outputs 3
Can you explain the working of the following code:

#include <stdio.h>

int main()
{    int a = - -3; 

    printf("a=%d", a);

    return 0;
}

In

int a = - -3;

this statement there is no --(decrement operator) , it is unary minus operator, which makes - -3 as 3(cancelling negation) . Hence it prints 3 .

Side note, if you think of this

int a = --3;

as prints 2 then you thinks wrong, as this cause lvalue error because -- applicable on variable not on constant. Correct one is

int a = 3;
--a ;/* this is valid,this make a as 2 now */

- -3 is a double and therefore cancelling negation.

It's an expression equal to 3. Apart from -INT_MIN which is undefined on a 2's complement system, a double negation is equivalent to the unary plus + .

If you had written --3 then the maximal munch rule would have compiled this as an attempt to decrement the constant 3 , which is not allowed, and compilation would fail.

a = - -3;

is parsed as

a = - (-3);

so you're negating a negative 3 , giving a positive 3 .

If you were intending to write

a = --3;

then you would have gotten a compile-time error, as the -- operator cannot be applied to constant expressions.

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