Loop Loop Loop

Which of the following is correct about the following loop in C?

1
2
3
4
5
6
7
8
#include <stdio.h>

int main(void) {
    char i;
    for (i=0; i <256; i++)
        printf("%d\n", i);
    return 0;
}

  • Assume that char is guaranteed to be of 8 bits.
Compilation Error Outputs all integers from 0 to 255 inclusive Infinite Loop Runtime Error

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Notice that char can essentially store information upto a byte. The loop works fine until i == 255 . But beyond that when it is incremented, it rolls back to i = 0 .

Since i always satisfies i < 256 , the loop is infinite.

I recommend the reader to verify this by running the code.

I'm running this code in c++. And output is quite different in c++.Because I guess char generally means signed char in c++. So it rolls back just after i=127. Same output can be achieved by declaring unsigned char.

Bal Krishna Jha - 3 years, 8 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...