0
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.

Karan
  • 43
  • 9

2 Answers2

4

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).

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
2

There are implicit conversions between all numeric types. The return of a function is one place these can occur.

For 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).

In the function you show, the result is representable as an int, except on common systems -INT_MIN is larger than INT_MAX.

Caleth
  • 52,200
  • 2
  • 44
  • 75