Reputation: 11
Will the accessibility of memory space get changed or just informing the compiler take the variable of mentioned type?
Example:
int main()
{
char a;
a = 123456789;
printf("ans is %d\n",(int)a);
}
Output:
overflow in implicit constant conversion a= 123456789.
ans is 21.
Here I know why it's causing overflow. But I want to know how memory is accessed when an overflow occurs.
Upvotes: 0
Views: 739
Reputation: 409206
This is kind of simple: Since char
typically only holds one byte, only a single byte of 123456789
will be copied to a
. Exactly how depends on if char
is signed
or unsigned
(it's implementation-specific which one it is). For the exact details see e.g. this integer conversion reference.
What typically happens (I haven't seen any compiler do any different) is that the last byte of the value is copied, unmodified, into a
.
For 123456789
, if you view the hexadecimal representation of the value it will be 0x75bcd15
. Here you can easily see that the last byte is 0x15
which is 21
in decimal.
What happens with the casting to int
when you print the value is actually nothing that wouldn't happen anyway... When using variable-argument functions like printf
values of a smaller type than int
will be promoted to an int
. Your printf
call is exactly equal to
printf("ans is %d\n",a);
Upvotes: 1