ming
ming

Reputation: 239

Why does this not produce an error?

I'm confused as to why this does not cause an error.

void f(int I) { 
  ++I;
  if (I > INT_MAX) {
    printf("OVERFLOW\n");
  } else {
    printf("NO OVERFLOW\n");
  }
}

int main(void) {
  f(INT_MAX);
  printf("DONE\n");
}

I'm coding in C, and my school defined INT_MAX for us already to be $2^{31} - 1$ I think is what it is.

Upvotes: 0

Views: 87

Answers (2)

Syed Waris
Syed Waris

Reputation: 1074

OVERFLOW will not be printed in your case. What is happening in your case is that: When your I is already at the maximum, and if you further increase it using ++I, it will wrap around to the lowest value. Illustration:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

void f(int I) {
  ++I;
  printf("\nAfter incrementing I: %d\n", I);
  if (I > INT_MAX) {
    printf("OVERFLOW\n");
  } else {
    printf("NO OVERFLOW\n");
  }
}

int main(void) {
  f(INT_MAX);
  printf("DONE\n");
}

Output:

After incrementing I: -2147483648
NO OVERFLOW
DONE

Upvotes: 1

Nyos
Nyos

Reputation: 414

This can give you NO OVERFLOW on two different routes:

  1. Your compiler has the right to optimize out your if statement. Since nothing of int type can be >INT_MAX, it's always false, thus your if is compiled to a simple printf("NO OVERFLOW\n");.
  2. For the other one you need to know 2-complement. If you add 1 to INT_MAX, it turns around, and becomes the smallest number an int can represent. So 2147483647+1=-2147483648, which doesn't make sense in maths, but here it's a design feature. This makes adding reasonably large negative numbers to positive numbers work well. Just you need to keep in mind to use the proper type to hold your numbers.

(I'm assuming a "normal" 32 bit int, but some architectures use different size, e.g. on AVR8 ints are 16 bit long.)

Upvotes: 1

Related Questions