Does an Integer variable in C occupy 2 bytes or 4 bytes? What are the factors that it depends on?
Most of the textbooks say integer variables occupy 2 bytes. But whe
Is the size of C “int” 2 bytes or 4 bytes?
The answer is "yes" / "no" / "maybe" / "maybe not".
The C programming language specifies the following: the smallest addressable unit, known by char
and also called "byte", is exactly CHAR_BIT
bits wide, where CHAR_BIT
is at least 8.
So, one byte in C is not necessarily an octet, i.e. 8 bits. In the past one of the first platforms to run C code (and Unix) had 4-byte int
- but in total int
had 36 bits, because CHAR_BIT
was 9!
int
is supposed to be the natural integer size for the platform that has range of at least -32767 ... 32767
. You can get the size of int
in the platform bytes with sizeof(int)
; when you multiply this value by CHAR_BIT
you will know how wide it is in bits.
While 36-bit machines are mostly dead, there are still platforms with non-8-bit bytes. Just yesterday there was a question about a Texas Instruments MCU with 16-bit bytes, that has a C99, C11-compliant compiler.
On TMS320C28x it seems that char
, short
and int
are all 16 bits wide, and hence one byte. long int
is 2 bytes and long long int
is 4 bytes. The beauty of C is that one can still write an efficient program for a platform like this, and even do it in a portable manner!