Why are 01 and 02 case different?
char c=0xAB;
printf("01:%x\n", c<<2); // fffffeac
printf("02:%x\n", c<<=2); //ffffffac
printf("03:%x\n", c<<=2);
Why are 01 and 02 case different?
char c=0xAB;
printf("01:%x\n", c<<2); // fffffeac
printf("02:%x\n", c<<=2); //ffffffac
printf("03:%x\n", c<<=2);
Implicit promotions.
You are on a system that uses twos complement for representing data in native machine format,
charis signed and has 8 bits andinthas 32 bits on your machine.The
cand2inc<<2are implicitly promoted toint, so it becomes(int)c << (int)2.cis0xAB,(int)cis sign-extended to 32 bits so it is0xffffffab. Then<<2happens so the resulting value is0xfffffeac.The
c <<= 2stores the value of0xfffffeacinsidecfirst, then the value of the whole expression becomes the value ofcafter the assignment. So the result ofc << 2being(int)0xfffffeacis converted tocharon assignment toc. Becausecharhas 8 bits on your machine, the value is truncated to 8 bits andcbecomes equal to0xac. Then again, default argument promotions happen for each argument that is a part of the variable argument list in a variable argument function call, likeprintf(const char *, ...);- each argument after..undergoes default argument promotions. So thencnow beeing equal to0xacis again sign-extended to 32 bits toint, so becomes0xffffffac.