有没有定义INT_MAX一个可移植的方法? [英] Is there a portable way to define INT_MAX?
问题描述
我发现在/usr/include/limits.h以下定义:
I found the following definitions in /usr/include/limits.h:
#定义INT_MIN(-INT_MAX - 1)
#定义INT_MAX 2147483647
另外,似乎在此头文件中的所有XXX_MAX的显式从数字常数定义
Also, it seems that all XXX_MAX's in this header file are explicitly defined from a numerical constant.
我(跨平台针对不同的字大小)不知道是否有一个可移植的方式来定义INT_MAX?
I wonder if there is a portable way (against different word sizes across platforms) to define a INT_MAX ?
我试过如下:
〜((INT)-1)
但这似乎不正确。
一个短的解释也高度重视。
A short explanation is also highly regarded.
推荐答案
对于 INT_MAX
在标准头 limits.h中
,实现者的手被它的要求是在preprocessor 可用#如果
指令的事实追平。这排除了任何涉及的sizeof
或转换。
For the INT_MAX
in the standard header limits.h
, the implementor's hands are tied by the fact that it's required to be usable in preprocessor #if
directives. This rules out anything involving sizeof
or casts.
如果你只是想在实际的C EX pressions使用的版本,也许这会工作:
If you just want a version that works in actual C expressions, perhaps this would work:
(int)-1U/2 == (int)(-1U/2) ? (int)-1U : (int)(-1U/2)
这里的概念是, INT
可能具有相同的数值位为无符号
,或者少一个值位; C标准允许使用。为了测试它是,检查转换结果(INT)-1U
。如果 -1U
在 INT
适合,其值必须是演员不变,所以平等是真实的。如果 -1U
不适合在 INT
,然后投结果类型的实现定义的结果 INT
。不管该值是什么,虽然,平等将假仅通过可能值的范围内。
The concept here is that int
may have the same number of value bits as unsigned
, or one fewer value bit; the C standard allows either. In order to test which it is, check the result of the conversion (int)-1U
. If -1U
fits in int
, its value must be unchanged by the cast, so the equality will be true. If -1U
does not fit in int
, then the cast results in an implementation-defined result of type int
. No matter what the value is, though, the equality will be false merely by the range of possible values.
请注意,从技术上,转换到 INT
可能会导致一个实现定义的信号被提出,而不是获得一个实现定义的值,但这不是会当你处理一个恒定的前pression这将在编译时进行评估的情况发生。
Note that, technically, the conversion to int
could result in an implementation-defined signal being raised, rather than an implementation-defined value being obtained, but this is not going to happen when you're dealing with a constant expression which will be evaluated at compile-time.
这篇关于有没有定义INT_MAX一个可移植的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!