在 C99 中,我包含stdint.h
和,这给了我UINT32_MAX
以及uint32_t
数据类型。但是,在 C++ 中UINT32_MAX
定义了。我可以在 include__STDC_LIMIT_MACROS
之前定义stdint.h
,但如果有人在包含他们自己之后包含我的标题,这将不起作用stdint.h
。
那么在 C++ 中,找出 a 中可表示的最大值的标准方法是uint32_t
什么?
不确定uint32_t
,但对于基本类型(bool
, char
, signed char
, unsigned char
, wchar_t
, short
, unsigned short
, int
, unsigned int
, long
, unsigned long
,和) float
,您可以通过.double
long double
numeric_limits
#include <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;
std::numeric_limits<T>::max()
定义 type 的最大值T
。
好吧,uint32_t 将始终是 32 位的,并且始终是无符号的,因此您可以安全地手动定义它:
#define UINT32_MAX (0xffffffff)
你也可以做
#define UINT32_MAX ((uint32_t)-1)
我无法发表评论,所以这是我对 Glen vs Lior Kogan 的回答的意见。
如果您使用的是静态变量,您将遇到这样的问题,即如果您在类中为 numeric_limits::max() 分配一个常量值,由于初始化的顺序,该值实际上将设置为零(请参阅这篇文章零初始化和局部范围静态变量的静态初始化)
因此,在这种情况下,它只能通过使用 Lior Kogan 的答案来工作。
// This looks cleaner, less error prone and easier to read than the other suggested by Lior Kogan
#define UINT32_MAX ((uint32_t)-1)
您可以#include
通过更改构建过程以__STDC_LIMIT_MACROS
在编译器命令行上定义符号来消除顺序问题:
cxx -D__STDC_LIMIT_MACROS ...
当然,如果标题#undef
是这个符号,你仍然会遇到麻烦。
此外,您正在使用的标准库实现的作者可能并不打算让用户设置该特定符号;用户可能会使用编译器标志或不同的符号来启用 C++ 中的 C99 类型。
任何无符号整数类型 T 的最大值是T(~T(0))
。