Elegant and safe way to determine if architecture is 32bit or 64bit

后端 未结 7 1510
北恋
北恋 2021-01-19 01:47

As title says, is there any elegant and safe way to determine if architecture is 32bit or 64bit. By elegant, you can think of precise, correct, short, clean, and smart way.

7条回答
  •  生来不讨喜
    2021-01-19 02:27

    The size of pointers isn't really a good thing to test - there's not much in standard C that you can do with the result of that test anyway.

    My suggestion is test ((size_t)-1), the largest object size that C understands:

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

    If it's greater than 0xffffffffUL then you can in principle have objects larger than 2**32 - 1 bytes, which seems like a more meaningful test than a nebulous "32 bits versus 64 bits".

    (For example, if you know that the maximum value of size_t is only 2**32 - 1, then there's no point trying to mmap() a region bigger than 1 or 2 GB.)

提交回复
热议问题