Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error occurred when I use variables in the shift operation of C

Tags:

c

Last night, my friend tell me a situation as following shows:

in c/c++ ,we write two lines code like this:

int a = 0;
printf("%d\n", 1 << -1);
printf("%d\n", 1 << (a-1));

It is amazing there are two different results, previous is 0, and the other is -2147483648.

We do not know why, and anyone can give me a help.

any word is welcome.

like image 533
CPT Avatar asked Nov 18 '25 06:11

CPT


1 Answers

Having a negative operand on the right hand side of a left-shift operator is undefined behavior in C. You shouldn't be amazed at any results from doing it.

like image 82
Crowman Avatar answered Nov 20 '25 22:11

Crowman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!