+ 7

For( char c=0;c<256;++c){}

Why this code run in infinity time

12th Mar 2019, 10:34 PM
Govindaraju C
Govindaraju C - avatar
5 Answers
+ 14
It is infinite in C/C++ because a char is 1 byte and its range is -128 to 127 for signed and 0 to 255 if unsigned, both of these ranges are always less than 256 so the condition is always true. In java I think a char is 2 bytes so it doesn't have this issue... at least not until 65536 ( if unsigned ). :)
12th Mar 2019, 11:01 PM
Dennis
Dennis - avatar
+ 8
After c is 127 the next increment updates the value of c to -128 which still satisfies the loop condition. https://code.sololearn.com/c6RfNKr2a22w/?ref=app
13th Mar 2019, 3:47 AM
Sonic
Sonic - avatar
+ 6
Your code does not run infinity. https://code.sololearn.com/cWrccvH9N0v5/?ref=app I think this works because every char has an ascii value --> ++c increment the ascii value of c
12th Mar 2019, 10:55 PM
Denise Roßberg
Denise Roßberg - avatar
+ 6
Dennis Thx. I didn't know this fact.
12th Mar 2019, 11:07 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
Your code, use int instead of char if you wanna count from 0 to 255: for(int c = 0;c <256;c++){ System.out.println(c); } Wanna loop through characters? for(char c = 'A';c <'Z';c++){ System.out.println(c); }
12th Mar 2019, 10:50 PM
JavaBobbo
JavaBobbo - avatar