Search code examples
c++expression

Data type used to store particular expression


This line of code wont work as intended, because the data type used to store the expression is integer, resulting in integer overflow in case of being greater than INT_MAX. if(y*10+modulo>INT_MAX) return 0;

This other line executes perfectly when same edge case is encountered. Where y,j are integers, and a is a vector of integers. What data type is used to store this second expression? if( y+a[i]*pow(10,j)>INT_MAX) return 0;

Additional context: In both cases reversing an integer is attempted, a[i] storing the digits of input number in reverse order, and j starting from size of a -1

To avoid confusion about the -1, a 3 digit number ex 123 can be written like this 1 * 10^2 + 2 * 10^1 + 3*10^0

I tried the first two things you do before coming here, asking google and ai about this case.


Solution

  • The "secret" is the call to pow; despite being given integer arguments, it only has float-type variants (in this case, I believe it defaults to double). This causes the entire expression to use a floating-point type, which does have a larger range than int.