Mohan
Mohan

Reputation: 29

Variable size allocated during assign operation

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.

Upvotes: 2

Views: 78

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320747

C language never performs arithmetic computations withing the domain of char, short or any other type that is smaller than int. Operands of arithmetic operators are promoted to int before the actual computations begin (assuming int can represent all values of the original type). So, your

a = b * 256 + c;

is actually interpreted by the compiler as

a = (int) b * 256 + (int) c;

In other words, expression b *= 256 would indeed overflow a char variable on assignment back to b, but expression b * 256 does not overflow by itself.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409462

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

Upvotes: 2

merlin2011
merlin2011

Reputation: 75629

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

 a = b*256 + c;

Upvotes: 6

Related Questions