Linux-Hams archive - July 1998: sizeof()

sizeof()

Mike Bilow (EEST)
Sun, 05 Jul 98 17:59:00 -0000


Karl F. Larsen wrote in a message to Mike Bilow:

KFL> I am learning to write C and yesterday tried to write a
KFL> program that used sizeof() and it is broken in my version of
KFL> compiler. No matter what kind of variable, the Linux
KFL> sizeof() returns 4. I went back to my old Borland DOS
KFL> compiler and it works there.

I can assure you that "sizeof()" is not broken an any compiler.

KFL> Please write this simple program on your Linux and see
KFL> what you get:

KFL> /* checks the function sizeof() */
KFL> #include <stdio.h>
KFL> int main(void)
KFL> {
KFL> printf("The size of an integer is %d bytes.\n",
KFL> sizeof(int)); return 0;
KFL> }

KFL> This prints 4 in Linux and 2 (which is correct) using
KFL> Borland C++.

The requirement of ANSI C is only that sizeof(short) <= sizeof(int) and
sizeof(int) <= sizeof(long). As long as these two conditions hold true, the
compiler is perfectly in compliance with ANSI C requirements on this issue.

The idea is that each compiler will choose to implement "int" with a size that
allows the most convenient or highest performance operations under its
particular circumstances. If you are using a 16-bit compiler, then you will
usually get a 16-bit "int" in that environment. If you are using a 32-bit
compiler, then you will usually get a 32-bit "int" there.

In fact, the way Intel processors are designed, it actually does impose
significant burdens to access registers using the opposite of your default
mode, so it is a very good idea to keep "int" the same size as the default
register size. Since Linux runs 32-bit code and GCC is a 32-bit compiler, you
get a 32-bit "int" for maximum efficiency.

If you have a real need to know the largest values representable in an "int" at
compile time, the ANSI-endorsed way to find this out is to use the manifest
constants "INT_MIN" and "INT_MAX" defined in LIMITS.H. In general, it is
considered good practice to avoid writing any code which depends upon the
underlying implementation size of "int" or any other data type.

-- Mike