4

This was asked in an interview. "There is a bug in the below function, what is it?". It is simple add c function and main function calls it. Given some clue -- "Give different set of input values, test and find bug".

int add (int x, int y)
{ 
    return x + y;
}

1 Answer 1

11

The problem can be integer overflow occurs if x+y is greater than INT_MAX or less than INT_MIN. So use long long as return type.

4
  • +1 of course, do you know an alternative to long long for compilers without support for C99? Commented Jul 4, 2013 at 9:40
  • You can use unsigned if you know that at least one of the numbers are greater than zero.
    – banarun
    Commented Jul 4, 2013 at 9:43
  • "at least one of the numbers are greater than zero", no, unsigned long x = -5 + 2 will fail, do you mean if the greater abs value is > 0? Commented Jul 4, 2013 at 10:03
  • No, I mean it wouldn't cause an overflow. We can evaluate the value even in your case. If the most significant bit in the return value is 0 do noting. If it is 1 , then find it's compliment.
    – banarun
    Commented Jul 4, 2013 at 10:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.