在C99中,我包含了stdint.h,它给了我UINT32_MAX以及uint32_t。但是,在C++中,UINT32_MAX被定义。在包含stdint.h之前,我可以定义__STDC_LIMIT_MACROS,但是如果有人在包含stdint.h之后包含我的头文件,则这种方法无效。什么是UINT32_MAX的C++等价物?
所以在C++中,找出uint32_t中可表示的最大值的标准方法是什么?
在C99中,我包含了stdint.h,它给了我UINT32_MAX以及uint32_t。但是,在C++中,UINT32_MAX被定义。在包含stdint.h之前,我可以定义__STDC_LIMIT_MACROS,但是如果有人在包含stdint.h之后包含我的头文件,则这种方法无效。什么是UINT32_MAX的C++等价物?
所以在C++中,找出uint32_t中可表示的最大值的标准方法是什么?
嗯,我不知道uint32_t
但基本类型(bool, char, signed char, unsigned char, wchar_t, short, unsigned short, int, unsigned int, long, unsigned long, float, double and 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
是上面比这个代码应开箱
cout << "Maximum value for uint32_t: " << numeric_limits<uint32_t>::max() << endl;
或者'uint32_t'是否是上述之一的'typedef'? – 2013-06-11 01:56:38
我当然希望它是一个typedef。如果你的工具使用'#define',我质疑它们的质量。 – John 2013-06-11 02:18:02
为了避免与std :: min()和std :: max()混淆numeric_limits :: min(),numeric_limits :: max(),我必须将它括在括号中,如下所示:(std :: numeric_limits ::最大)(); – 2013-11-07 16:20:47
std::numeric_limits<T>::max()
定义了类型为T
的最大值。
您可以消除通过改变你的构建过程中的#include
治安问题来定义编译器命令行而不是在__STDC_LIMIT_MACROS
符号:
cxx -D__STDC_LIMIT_MACROS ...
当然,你仍然有麻烦,如果一个头#undef
这是这个符号。
此外,您正在使用的标准库实现的作者可能没有打算让用户设置该特定符号;可能会有一个编译器标志或用户打算用来在C++中启用C99类型的不同符号。
我不能评论,所以这里是我对Glen与Lior Kogan的回答的投入。
如果你使用的是静态变量,你会遇到这样的问题,如果你在一个类中为一个常量赋值给numeric_limits :: max(),那么这个值实际上会因为初始化的顺序而被设置为零(参见这篇文章zero initialization and static initialization of local scope static variable)
所以在那种情况下,它只会使用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)
死灵侧面说明:'#包括'在C++ –
AJG85
2011-06-09 16:00:50
@ AJG85有正确的答案。 – 2014-08-26 15:31:21