Search code examples
c++c++11intlong-integer

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;
        
    }

How is this code valid? It's clear that result is a long long variable but the return type of the code is int. The code still works.


Solution

  • The return value will silently be truncated if the value exceeds the range of int.

    Your compiler likely has warnings you can enable that tells you this. You should enable them (and also ask it to turn warnings into errors IMHO).