1

Can anyone explain to me why this code prints "error" ? This only appears for minimal value of integer.

int abs(int x) {
    int result = 0;
    if(x < 0)
        result = -1*x;
    else 
        result = x;

    return result;
}

int main() {

    printf("Testing abs... ");
    if (abs(-2147483648) != 2147483648)
        printf("error\n");
    else
        printf("success\n");
}
1
  • have you tried int a = -2147483648; int b = 2147483648; printf("%d %d", a, b);? Commented Feb 18, 2012 at 0:29

5 Answers 5

7

Because for a 32 bit integer signed integer, using two's complement, the largest number you can store is 2147483647.

The range is -2147483648 2147483647.

You must be careful - overflowing signed numbers is undefined behavior.

Sign up to request clarification or add additional context in comments.

Comments

0

The maximal value of a 32 bit integer is 2,147,483,647.

Comments

0

put long instead of int. For bigger integers you will need long long. Google for the range that this types offer. Also for the comparison with a static number you must declare it like e.g. 8438328L

1 Comment

Using long won't help on 32-bit Linux, 32-bit OS X, or any flavor of Windows.
0

Because of the way integers are represented (2's complement), if your int is 32 bits, -2147483648 is its own negative.

After -2147483648 is returned by your abs(), it is probably being compared as a long, 64-bit integer. If the comparison were 32-bit, 2147483648 would be equivalent to -2147483648. Perhaps if you turn on all warnings for your compiler, it will complain?

Comments

0

The range of 32-bit signed integers is, as has been mentioned before -2147483648 (= -231) to 2147483647 (= 231 - 1). In your abs() function, you have thus overflow of a signed integer, which is undefined behaviour (citation of standard to be inserted). Therefore anything could happen, but what actually happens is very probably that the result just wraps around, producing -2147483648 again. However, you compare that to the integer literal 2147483648, which does not fit into a 32-bit signed integer, hence, since it has no (n)signedness suffix, that literal has the next type in the list

  1. int
  2. long int
  3. long long int

which can represent its value (if any). On 64-bit systems that could be long int or long long int, the former is typically the case on Linux, the latter, as far as I know on Windows, on 32-bit systems it's almost certainly long long int.

Then the int value -2147483648 is promoted to long (long) int and the tested condition is

if (-2147483648L != 2147483648L)  // or LL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.