在 C99 中,我可以包含 stdint.h
头文件,获得 UINT32_MAX
和 uint32_t
数据类型。然而,在 C++ 中,UINT32_MAX
没有被定义。我可以在包含 stdint.h
之前定义 __STDC_LIMIT_MACROS
,但如果有人在已经包含了 stdint.h
的情况下再包含我的头文件,则这种方法不起作用。
那么,在 C++ 中,找出可表示的最大值 uint32_t
的标准方法是什么?
对于基本类型 (bool
, char
, signed char
, unsigned char
, wchar_t
, short
, unsigned short
, int
, unsigned int
, long
, unsigned long
, float
, double
和 long double
),你可以使用 #include <limits>
中的 numeric_limits
模板。
cout << "Minimum value for int: " << numeric_limits<int>::min() << endl;
cout << "Maximum value for int: " << numeric_limits<int>::max() << endl;
如果uint32_t
是上述其中之一的#define
,那么这段代码应该能够直接使用
cout << "Maximum value for uint32_t: " << numeric_limits<uint32_t>::max() << endl;
uint32_t
是以上类型之一的typedef
呢? - Craig McQueen#define
,那我就会质疑它们的质量。 - Johnstd::numeric_limits<T>::max()
定义了类型 T
的最大值。
uint32_t始终为32位,并且始终为无符号数,因此您可以安全地手动定义它:
#define UINT32_MAX (0xffffffff)
你也可以这样做。#define UINT32_MAX ((uint32_t)-1)
// This looks cleaner, less error prone and easier to read than the other suggested by Lior Kogan
#define UINT32_MAX ((uint32_t)-1)
T(~T(0))
。您可以通过更改构建过程,在编译器命令行上定义__STDC_LIMIT_MACROS
符号来消除#include
顺序问题:
cxx -D__STDC_LIMIT_MACROS ...
当然,如果头文件中使用了 #undef
指令取消该符号,则您仍可能遇到麻烦。
此外,您使用的标准库实现的作者可能不希望用户设置该特定符号;可能会有编译器标志或其他符号供用户使用以在 C++ 中启用 C99 类型。
#include <cstdint>
。 - AJG85