Why do we define INT_MIN as -INT_MAX - 1? [duplicate]

假装没事ソ 提交于 2019-11-27 15:47:01

Because 2147483648 is a long value as it does not fit in an int (in common system with 32-bit int and 64-bit long, on system with 32-bit long it is of type long long). So -2147483648 is of type long, not int.

Remember in C, an unsuffixed decimal integer constant is of the first type int, long or long long where it can be represented.

Also in C -2147483648 is not a integer constant; 2147483648 is an integer constant. -2147483648 is an expression formed with the unary operator - and the integer constant 2147483648.

EDIT: if you are not convinced -2147483648 is not of type int (some people in the comments still seem to doubt), you can try to print this:

printf("%zu %zu\n", sizeof INT_MIN, sizeof -2147483648);

You will most likely end up with:

4 8

on common 32 and 64-bit systems.

Also to follow a comment, I'm talking about recent C Standard: use c99 or c11 dialect to test this. c89 rules for decimal integer constant are different: -2147483648 is of type unsigned long in c89. Indeed in c89 (it is different in c99, see above), a unsuffixed decimal integer constant is of type int, long or unsigned long.

EDIT2: @WhozCraig added another example (but for C++) to show -2147483648 is not of type int.

The following example, though in C++, drives home this point. It was compiled with a 32-bit architecture g++. Note the type info gathered from the passed parameter deduction:

#include <iostream>
#include <climits>

template<typename T>
void foo(T value)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
    std::cout << value << '\n';
}

int main()
{
    foo(-2147483648);
    foo(INT_MIN);
    return 0;
}

Output

void foo(T) [T = long long]
-2147483648
void foo(T) [T = int]
-2147483648

Because this way you need only one magic number for two constants. If INT_MAX changes INT_MIN changes accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!