int 函数如何能够 return long long 变量?

How is an int function able to return long long variable?

int reverse(int x) {
        if(x==0)
            return 0;
        int y = abs(x);
        long long result = 0;
        while(y > 0) {
            result *= 10;
            result += y % 10;
            y /= 10;
        }
        if(result > INT_MAX || result < INT_MIN)
            return 0;
        if(x<0) {
            return -result;
        }
        return result;
        
    }

此代码如何有效?很明显 result 是一个 long long 变量,但是代码的 return 类型是 int。代码仍然有效。

如果值超出 int 的范围,return 值将被静默截断。

您的编译器可能有警告,您可以启用它告诉您这一点。您应该启用它们(并要求它把警告变成错误恕我直言)。

所有数字类型之间有implicit conversions。函数的 return 是这些可能发生的地方之一。

对于 long long -> int

If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined. (Note that this is different from signed integer arithmetic overflow, which is undefined).

在您显示的函数中,结果可表示为 int,除了在常见系统上 -INT_MIN 大于 INT_MAX