C Programming – Range of Values Stored in an Integer Type

c

C has family of integer types i.e {short, int, long, long long}. Any new programmer is likely to use int to represent integer variable in the application and since int type has 32 bit space with range (-2,147,483,648 to 2,147,483,647), there will be bug as soon value of the variable goes out of the range. As you can see the maximum value is 2,147,483,647 which IMHO very small (cannot even count Earth's population).

So my question is how does newbie avoid such bug? What is space of int type on 64 bit OS?

Best Answer

Note: 'int' is only guaranteed to be at least 16 bits. It's even smaller than you thought! If you want to guarantee at least 32-bits use 'long'. For even larger values look at things like 'int64_t' or 'long long'.

How does a newbie avoid problems like this? I'm afraid it's the same as for many other programming problems. "think carefully and take care".

Running a test at program startup is a good idea. As is having a good set of unit tests. Take extra care when moving to a new platform.