int 的最大值
是否有任何代码可以在 C/C++ 中查找整数的最大值(根据编译器),如 java 中的 Integer.MaxValue
函数?
Is there any code to find the maximum value of integer (accordingly to the compiler) in C/C++ like Integer.MaxValue
function in java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 C++ 中:
然后使用
std::numeric_limits
是一个模板类型,可以用其他类型实例化:在 C 中:
然后使用
或
In C++:
then use
std::numeric_limits
is a template type which can be instantiated with other types:In C:
then use
or
我知道这是一个老问题,但也许有人可以使用这个解决方案:
到目前为止,我们的结果是-1,直到 size 是一个有符号的整数。
正如标准所说,如果变量有符号且为负,则移入的位为 1;如果变量为无符号或有符号且正,则移入的位为 0。
由于 size 是有符号且为负数,我们将移入符号位 1,这没有多大帮助,因此我们转换为 unsigned int,强制移入 0,将符号位设置为 0,而让所有其他位保持为 1。
我们还可以使用掩码和异或,但随后我们必须知道变量的确切位大小。通过位前移位,我们不必随时知道 int 在机器或编译器上有多少位,也不需要包含额外的库。
I know it's an old question but maybe someone can use this solution:
So far we have -1 as result 'till size is a signed int.
As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.
As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.
We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.
这是我用来获取有符号整数的最大值的宏,该宏与所使用的有符号整数类型的大小无关,并且 gcc -Woverflow 不会抱怨
Here is a macro I use to get the maximum value for signed integers, which is independent of the size of the signed integer type used, and for which gcc -Woverflow won't complain
好吧,我既没有代表对(Philippe De Muyter)之前的答案发表评论,也没有提高它的分数,因此一个新的例子使用他的 define 为 SIGNED_MAX 简单地扩展为无符号类型:
与使用这个或那个标头不同,这里我们使用编译器的真实类型。
O.K. I neither have rep to comment on previous answer (of Philippe De Muyter) nor raise it's score, hence a new example using his define for SIGNED_MAX trivially extended for unsigned types:
Unlike using this or that header, here we use the real type from the compiler.
为什么不写一段这样的代码:
Why not write a piece of code like:
它可能依赖于体系结构,但至少在我的设置中确实有效。
It might be architecture dependent but it does work at least in my setup.