-7

I am currently learning C, and I made a program that I thought would give me the maximum integer value, but it just loops forever. I can't find an answer as to why it won't end.

#include <stdio.h>

int main()
{
    unsigned int i = 0;
    signed int j = i;
    for(; i+1 == ++j; i++);
    printf(i);
    return 0;
}

Any help would be appreciated, thank you!

  • 2
    This code doesn't compile, the printf is incorrect. Do you have warnings turned on in your compiler? This isn't an exact duplicate, but it should help you understand what is happening. https://stackoverflow.com/questions/17293749/sizeof-operator-in-if-statement – Retired Ninja Jan 18 '18 at 03:34
  • You're experiencing unsigned integer overflow. The output should hint that something's up when i starts back at zero again. – Austin Brunkhorst Jan 18 '18 at 03:34
  • What will terminate a loop that uses `i = 1, j = 0` and tests `i == ++j` then increments `i` and does the same test again?? (e.g. `1 == 1`, `2 == 2`, etc..) – David C. Rankin Jan 18 '18 at 03:53
  • 1
    You're also experiencing *signed integer overflow*, `runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'`, which makes the behaviour of your program as a whole, undefined. How do you think you could deduce the maximum integer value like this *at all*? – Antti Haapala -- Слава Україні Jan 18 '18 at 03:55
  • related: https://stackoverflow.com/questions/45882317/finding-maximum-value-of-a-short-int-variable-in-c – Antti Haapala -- Слава Україні Jan 18 '18 at 03:56
  • Maybe it is trying to tell you that there's no such thing as maximum integer value? – AnT stands with Russia Jan 18 '18 at 04:12
  • Copy/paste code that you have tested. Don't just transcribe from printed text and post - you will make typos and waste everyone's time:( – Martin James Jan 18 '18 at 07:08

2 Answers2

4

Your code has undefined behavior. And that's not because of unsigned integer overflow (it wraps when the value is too big). It is the signed integer overflow that is undefined behavior.

Also note that if your intention is to know the maximum value that an int can hold use the macro INT_MAX.

 maximum value for an object of type int
 INT_MAX                                +32767 // 215 - 1

Your should write the printf properly. (Pass the format specifier then the other arguments as specified by format specifier).

user2736738
  • 30,591
  • 5
  • 42
  • 56
3

I thought would give me the maximum integer value

The maximum signed int value cannot be portably found experimentally with out risking undefined behavior (UB). In OP's code, eventually ++j overflows (UB). UB includes loops forever.

As @coderredoc well answered, instead use printf("%d\n", INT_MAX);


To find the maximum unsigned value:

printf("%u\n", UINT_MAX);
// or 
unsigned maxu = -1u;
printf("%u\n", maxu);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256