Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable size allocated during assign operation

Tags:

c

int main()
{
     int a;
     char b,c;
     b=0x32;
     c=0x24;
     a=b*256+c;
     printf("a=%#x\n",a);
     return 0;
}

Output:

a=0x3224

Size of b is 1 byte; b*256 is a overflow for a char variable. Does the compiler allocate 2 different 16 bit registers for this operation? int is 16 bits over here.

like image 269
Mohan Avatar asked Mar 16 '26 18:03

Mohan


2 Answers

In the multiplication by the literal 256 on the following line, the char is promoted to an int before multiplication.

 a = b*256 + c;
like image 97
merlin2011 Avatar answered Mar 21 '26 09:03

merlin2011


No it doesn't overflow. Instead the contents of variable b (as well as c) are promoted to the type int.

like image 33
Some programmer dude Avatar answered Mar 21 '26 08:03

Some programmer dude



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!