-1
unsigned int i;

for (i = 100; i >=0; --i)
     printf("%d\n", i);

I ran this code on ideone and it prints until -10000

https://ideone.com/1TQ3Yu

  • 4
    What do you *expect* to happen? (it should actually endlessly print out numbers) – Amit Jan 16 '16 at 22:37
  • 7
    `unsigned int i;` --> `int i;` – BLUEPIXY Jan 16 '16 at 22:38
  • @Amit I think ideone.com has a limit to prevent infinite output. – Barmar Jan 16 '16 at 22:42
  • @Barmar - I assume that too. my comment is about what the code should do "in the real world". – Amit Jan 16 '16 at 22:43
  • 2
    Didn't your compiler give you any warnings? It should have flagged up the useless comparison in your `for()` loop, and your use of a signed format specifier (`%d`) to print an unsigned variable. Get into the habit of always compiling your code with warnings switched on (by using the `-Wall` command line flag). And learn how to use a debugger. – r3mainer Jan 16 '16 at 22:45
  • 1
    A **real** compiler would have warned against signed/unsigned comparison. Ideone seems to work on a pre-ansi compiler. – Frankie_C Jan 16 '16 at 22:54
  • @Frankie_C Ideone uses GCC 5.1, according to the language selection box. Maybe they just suppress the warnings. – user4520 Jan 16 '16 at 23:15
  • @szczurcio Maybe they suppressed **a lot of warnings** :-D. It suppressed other warnings here:http://stackoverflow.com/questions/34830416/purpose-of-void/34831267#34831267 – Frankie_C Jan 16 '16 at 23:28

2 Answers2

2

Since i is unsigned, it will always be >=0

Using the format string %d interprets it as a signed integer when printing. To view it unsigned, use %u.

Yosef Weiner
  • 5,432
  • 1
  • 24
  • 37
1

unsigned i will always be >=0, so int should be used instead of unsigned int in this case.

The problem is that i becomes (or wants to become) negative, but since it's an unsigned int, it stays positive and loops forever (-1 = 0xffffffff in 32-bit).

Danny_ds
  • 11,201
  • 1
  • 24
  • 46