What's the difference between unsigned long/long/int in c/c++?

user198729 picture user198729 · Mar 31, 2010 · Viewed 48.6k times · Source

It seems all of them take 4 bytes of space,

so what's the difference?

Answer

rlbond picture rlbond · Mar 31, 2010

First of all, the size of int/long is unspecified. So on your compiler, an int and a long might be the same, but this isn't universal across compilers.

As for the difference between unsigned long and long:

Assuming 4 bytes, a long has the range of -2,147,483,648 to 2,147,483,647. An unsigned long has the range of 0 to 4,294,967,295.

One other difference is with overflow. For a signed type, an overflow has unspecified behavior. But for an unsigned type, overflow is guaranteed to "wrap around."