Is there a way to find out if the machine is 32-bit or 64-bit by writing some code in C?
#include <limits.h>
/* ... */
printf("This machine's pointers to void, in a program "
"compiled with the same options as this one and "
"with the same compiler, use %d bits\n",
(int)sizeof (void*) * CHAR_BIT);
If by "some code in C" you mean standard C code, then the answer is no, it is not possible. For a C program, the "world" it can see is created entirely by the implementation (by the compiler). The compiler can emulate absolutely any "world", completely unrelated to the underlying hardware.
For example, you can run a 32-bit compiler on a 64-bit machine and you will never be able to detect the fact that this is a 64-bit machine from your program.
The only way you can find out anything about the machine is to access some non-standard facilities, like some OS-specific API. But that goes far beyond the scope of C language.
Needless to add, the already suggested in other answers methods based on sizeof
and other standard language facilities do not even come close detect the bit-ness of the machine. Instead they detect the bit-ness of the platform provided by the compiler implementation, which in general case is a totally different thing.
The pointer size
sizeof (void *) * CHAR_BIT
is a good indicator, but might be misleading on more exotic architectures (eg if the size of the address bus is no multiple of the word size) and only represent the execution environment (which might be different from the actual hardware - see AndreyT's answer).
During the preprocessing phase, the best you can do within the framework of the C language is something like
UINTPTR_MAX == UINT64_MAX
The same limitations as above apply.
There is no such thing as 32 bit or 64 bit environments, this is just too much of an oversimplification. You have several characteristics of integer, pointer, and float sizes that come into play if you want to write a portable application.
The size of your different integer types can be checked with the appropriate macros such as UINT_MAX
etc, pointer size by UINTPTR_MAX
. Since there might be padding bits, to deduce the width of the types you should print something like (unsigned long long)(T)-1
where T
is an unsigned type.