1827313 Members
2385 Online
109961 Solutions
New Discussion

int overflow

 
Max_4
Frequent Advisor

int overflow

Hi all,

I was wondering what would happen If I did the following declaration and initialization:

signed char a = 256;

Since a char is only 8 bits its maximun is 255.

I've tested this printf("%x\n", a); and got zero as a result...??

What does really happen when we overflow the system defined limits of basic integer types?

I assume the same would happen when I do for example:

short s_int = 65536;

The answer of printf("%hd\n", s_int); is 0

If I did
short s_int = 65537;

then the answer will be 1.

Is there a way to predict this behaviour...?

What really happens when we overflow these int types...?


Thanks a lot to everybody in advance....

Max
1 REPLY 1
A. Clay Stephenson
Acclaimed Contributor

Re: int overflow

The behavior of integer overflow is undefined although what you have found is typical. The proper way to deal with this is to use the limits found in /usr/include/limits.h which define the maximum and minimum values for vaarious data types on your platform.
If it ain't broke, I can fix that.