Your C textbook might say sizeof(int) = 2, and another might say its 4 actually! Quite confusing, and yet both are wrong. If your textbook say its either 2, 4 or something else, its either old or wrong! One way or the other, its time to look for a new book!
The C standard mentions nothing about the size of int or other primitive data types. All it does mention is a range of integers it can hold, and in case of int, -32768 to 32767, which requires 16 bits or 2 bytes minimum.
The keyword here is minimum. Int should be able to hold atleast any numbers within -32768 to 32767, or should be 2 bytes in size minimum. But compilers are free to go beyond that minimum. On 32-bit and most 64-bit systems, you shall see sizeof(int) = 4.
Lets write a simple C program.
printf(”Sizeof int = %d\n”, sizeof(int));
printf(”Sizeof int* = %d\n”, sizeof(int*));
In 16-bit systems, sizeof int shall probably be 16 bits or 2 bytes. On 32-bit systems, sizeof int shall probably be 32 bits or 4 bytes. But when you run it on 64-bit systems, you might be expecting 64 bits or 8 bytes due to the word size. But chances are, sizeof int in 64 bit systems shall still be 4 bytes.
The interesting thing to note here is sizeof(int*), which is same as the word size of your processor. On 64-bit systems, sizeof(int*) = 8 bytes, and on 32-bit systems, its 4 bytes.
Another thing worth mentioning is about sizeof(long) and sizeof(short). On your system, sizeof(int), sizeof(long), sizeof(short) might have the same value. All C standard mentions is the range of values:
long: 2147483648 to 2147483647
All the above are signed values. Since short, int, long can be held in a 4 byte memory, chances are sizeof int, short, long shall be 4 bytes (if you are having a 64 bit system).
A couple of things to remember:
A short int must not be larger than an int.
An int must not be larger than a long int.
A short int must be at least 16 bits long.
An int must be at least 16 bits long.
A long int must be at least 32 bits long.
A long long int must be at least 64 bits long.
if you need to understand why compilers choose these sizes, have a look though: http://www.unix.org/version2/whatsnew/lp64_wp.html
But sizeof(char) is fixed and is 1 byte. If you need bigger width char types, have a look at the wide character data type - wchar_t.
To fix this discrepancy, C99 introduced some fixed width integers like int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t. They are defined in <stdint.h>. Irrespective of the compiler or the machine you use, their size is fixed. Just don’t forget to turn on the C99 mode!