Checking the sizeof an integer type in the preprocessor

自闭症网瘾萝莉.ら 提交于 2020-01-02 01:01:09

问题


How can I check the size of an unsigned in the preprocessor under g++? sizeof is out of the question since it is not defined when during preprocessing.


回答1:


This may not be the most elegant method, but one thing that you may be able to leverage is UINT_MAX defined in "limits.h". That is, ...

if UINT_MAX == 65535, then you would know that sizeof (unsigned) = 2

if UINT_MAX == 4294967295, then you would know that sizeof (unsigned) = 4.

and so on.

As I said, not elegant, but it should provide some level of usability.

Hope this helps.




回答2:


Based on Sparky's answer, here is a way that would look a bit nicer (by eliminating the explicit numbers)

#include <limits.h>
#include <stdint.h>

//Check if size if 4bytes
#if UINT_MAX == UINT32_MAX

....

#endif

<limits.h> defines INT_MAX and <stdint.h> defines UINT32_MAX. Generally, <stdint.h> gives integer types with specified widths.



来源:https://stackoverflow.com/questions/2584937/checking-the-sizeof-an-integer-type-in-the-preprocessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!