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

后端 未结 7 1590
北恋
北恋 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:22

    A safe and portable technique is unfortunately impossible (because safe and portable only allows you the rules in the C Standard).

    sizeof(int) with some of the more common compilers may give you 4 for a 32 bit platform and 8 for a 64 bit platform but this is not guaranteed. All the C standard says is that an int should be the 'natural' size for calculations on the target, and so many compilers have left sizeof(int) as 4 even in a 64 bit world, on the grounds that it is 'enough'.

    sizeof(void*) is better because a pointer must be the appropriate size to address the whole address space. sizeof(void*) is therefore likely to give you 4 or 8 as appropriate. Technically though, even this isn't guaranteed as a sizeof gives you the number of bytes needed to store something, and a byte doesn't have to be 8 bits. A byte is technically the smallest addressable unit of memory which just happens to be 8 bits on most platforms people are used to. 8 bit addressable is very common, but I work with chips that are 16 bit addressable and 16 bit word size (so sizeof(int) is 1). So, if your byte size is not 8 bit, then sizeof(void*) could give you a variety of values.

    On the other hand, if you are merely trying to differentiate between x86 and x64 (32bit and 64 bit PC processors) then sizeof(void*) will be sufficient, and portable across compilers.

提交回复
热议问题