An elegant and secure way to determine if an architecture is 32-bit or 64-bit

As the title says, is there an elegant and secure way to determine if an architecture is 32-bit or 64-bit. Thanks to elegance, you can think in a precise, correct, short, clean and smart way. Safe, think about security in terms of standard, C89 / C99 and operating system independence.

+5
source share
7 answers

The size of the pointers is actually not very well checked - there is not much in the C standard that you can do with the result of this test.

- ((size_t)-1), , C:

    if ((size_t)-1 > 0xffffffffUL)
    {
            printf("> 32 bits\n");
    }
    else
    {
            printf("<= 32 bits\n");
    }

, 0xffffffffUL, 2**32 - 1 , , "32 64 ".

(, , size_t - 2**32 - 1, mmap() 1 2 .)

+3

:

: OS/. , linux proc, .

, , , 32/64 , - :

bool is_32bit() {
    return sizeof(int *) == 4;
} 

bool is_64bit() {
    return sizeof(int *) == 8;
} 

(, ). #define , .

+9

GCC ( ), ,

#if __SIZEOF_POINTER__ == 8

, 64- . , GCC __SIZEOF_POINTER__ , .

+7

sizeof(void*) sizeof(int) ( , ).

x86/x64 - "lm". , CPU AMD64.

+2

, , ( C).

sizeof(int) 4 32- 8 64- , . C , int "" , sizeof (int) 4 64- , "",.

sizeof(void*) , . sizeof(void*) , , 4 8, . , , sizeof , -, 8 . - , , , 8 , . 8- , , 16- 16- ( sizeof(int) 1). , 8 , sizeof(void*) .

, x86 x64 (32- 64- ), sizeof (void *) .

+2

32- 32- .:-) 8086 16- 20- . , Havard /...

cpuid x86. ... YMMV.

+1
int iedx;

__asm
{

mov eax, 0x80000001;
cpuid;
mov, iedx,edx;
}

     if (iedx & (1 << 29))
       {
        return 1;
       }
     return 0;
+1