如何检查是否定义了固定宽度的整数 [英] How to check if fixed width integers are defined
问题描述
在 C++ 中,固定宽度的整数被定义为 optional,但我可以'似乎没有找到推荐的方法来检查它们是否被实际定义.
In C++, fixed width integers are defined as optional, but I can't seems to find the recommended way to check if they are actually defined.
检查固定宽度整数是否可用的便携式方法是什么?
What would be a portable way to check if fixed width integers are available?
推荐答案
要确定是否提供了定宽整数类型,可以检查是否有对应的[U]INT*_MAX
或 [U]INT*_MIN
宏已定义.
To determine if a fixed-width integer type is provided, you can check if either of the corresponding [U]INT*_MAX
or [U]INT*_MIN
macros is defined.
// may be necessary for your C++ implementation
#define __STDC_LIMIT_MACROS
#include <cstdint>
#ifdef INT32_MAX
// int32_t must be available to get here
int32_t some32bitIntVariable;
#endif
根据 7.20 整数类型
,C11 标准第 4 段(注意加粗部分):
Per 7.20 Integer types <stdint.h>
, paragraph 4 of the C11 standard (note the bolded parts):
对于实现提供的此处描述的每种类型,
应声明typedef
名称并定义关联的宏.相反,对于实现未提供的此处描述的每种类型,
不应声明 typedef
name 也不应定义关联的宏.
For each type described herein that the implementation provides,
<stdint.h>
shall declare thattypedef
name and define the associated macros. Conversely, for each type described herein that the implementation does not provide,<stdint.h>
shall not declare thattypedef
name nor shall it define the associated macros.
C++ 通过
继承了 C 实现.参见
与
一些细节.另请参阅 __STDC_LIMIT_MACROS 的作用
和 __STDC_CONSTANT_MACROS
是什么意思? 有关 __STDC_LIMIT_MACROS
的详细信息.
C++ inherits the C implementation via <cstdint>
. See <cstdint>
vs <stdint.h>
for some details. Also see What do __STDC_LIMIT_MACROS
and __STDC_CONSTANT_MACROS
mean? for details on __STDC_LIMIT_MACROS
.
因此,如果 int32_t
可用,INT32_MAX
和 INT32_MIN
必须是 #define
.相反,如果 int32_t
不可用,则 INT32_MAX
和 INT32_MIN
都不允许被 #define
处理.
Thus, if int32_t
is available, INT32_MAX
and INT32_MIN
must be #define
'd. Conversely, if int32_t
is not available, neither INT32_MAX
nor INT32_MIN
are allowed to be #define
'd.
请注意,正如@NicolBolas 在另一个答案中所述,可能没有必要实际检查.
Note though, as @NicolBolas stated in another answer, it may not be necessary to actually check.
这篇关于如何检查是否定义了固定宽度的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!