32-bit or 64-bit? Using C code

Is there a way to find out if a machine is 32-bit or 64-bit by writing some code in C?

+4
source share
5 answers
#include <limits.h> /* ... */ printf("This machine 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); 
+8
source

If by "some code in C" you mean the standard code C, then the answer is "no", this is impossible. For program C, the "world" that he sees is completely created by the implementation (compiler). The compiler can emulate absolutely any "world" that is completely unrelated to the basic equipment.

For example, you can run a 32-bit compiler on a 64-bit machine, and you can never find that it is a 64-bit machine from your program.

The only way to learn something about the machine is to access some non-standard tools, for example, a specific API. But that goes far beyond C.

It is unnecessary to add that the ones already proposed in other response methods, based on sizeof and other standard language tools, do not even detect the proximity of the machine. Instead, they discover the platform’s bit platform provided by the compiler implementation, which in the general case is completely different.

+7
source

There is no such thing as a 32-bit or 64-bit environment, this is too much of a simplification. You have several characteristics of integer, index, and floating sizes that come into play if you want to write a portable application.

The size of your different integer types can be checked using the appropriate macros, such as UINT_MAX , etc., the size of the pointer to UINTPTR_MAX . Since there may be padding bits in order to infer the width of the types, you should print something like (unsigned long long)(T)-1 , where T is an unsigned type.

+1
source

Pointer size

 sizeof (void *) * CHAR_BIT 

is a good indicator, but it can be misleading on more exotic architectures (for example, if the address bus size is not a multiple of the word size) and represent only the runtime environment (which may differ from real equipment - see AndreyT's answer ).

In the preprocessing phase, the best you can do with the C language is something like

 UINTPTR_MAX == UINT64_MAX 

The same restrictions as above apply.

0
source

Yes, if the CPUID command is used on the x86 processor:

http://en.wikipedia.org/wiki/CPUID

0
source

All Articles