Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What determines the size of integer in C? [duplicate]

Tags:

c++

c

sizeof

Possible Duplicate:
size of int, long, etc
Does the size of an int depend on the compiler and/or processor?

I'm not sure if similar questions have been asked before on SO (Atleast, I couldn't find any while searching, so thought of asking myself).

What determines the size of int (and other datatypes) in C. I've read it depends on the machine/operating system/compiler, but haven't come across a clear/detailed enough explanation on things like what overrides the other, etc. Any explanation or pointers will be really helpful.

like image 824
Raj Avatar asked Dec 02 '22 20:12

Raj


2 Answers

Ultimately the compiler does, but in order for compiled code to play nicely with system libraries, most compilers match the behavior of the compiler[s] used to build the target system.

So loosely speaking, the size of int is a property of the target hardware and OS (two different OSs on the same hardware may have a different size of int, and the same OS running on two different machines may have a different size of int; there are reasonably common examples of both).

All of this is also constrained by the rules in the C standard. int must be large enough to represent all values between -32767 and 32767, for example.

like image 163
Stephen Canon Avatar answered Dec 04 '22 11:12

Stephen Canon


int is the "natural" size for the platform, and in practice that means one of

  • the processor's register size, or

  • a size that's backward compatible with existing code-base (e.g. 32-bit int in Win64).

A compiler vendor is free to choose any size with ≥ 16 value bits, except that (for desktop platforms and higher) a size that doesn't work with OS' API will mean that few if any copies of the compiler are sold. ;-)

like image 37
Cheers and hth. - Alf Avatar answered Dec 04 '22 10:12

Cheers and hth. - Alf