Is there a portable way to define INT_MAX?

c, gcc, int

Solution

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.

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)

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.

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.

Problem

I found the following definitions in /usr/include/limits.h: `# define INT_MIN (-INT_MAX - 1)` `# define INT_MAX 2147483647` Also, it seems that all XXX_MAX's in this header file are explicitly defined from a numerical constant. I wonder if there is a portable way (against different word sizes across platforms) to define a INT_MAX ? I tried the following: `~((int)-1)` But this seems incorrect. A short explanation is also highly regarded.

Original source