Why this code runs infinitely? Plz leave a comment abt this! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why this code runs infinitely? Plz leave a comment abt this!

#include <iostream> using namespace std; int main() { for(char x=0; x<256; ++x) { cout <<x; } return 0; }

10th Apr 2017, 1:58 AM
Çhandra_Şhekar
Çhandra_Şhekar - avatar
6 Answers
+ 8
The default encoding in a compiler is set to ASCII-7, which means 7 bits are allocated... So, by default there are only 128 characters available to you... // 2^7=128 To get more like till 256, you will have to change the encoding to ASCII-8 in your compiler or IDE... // 2^8=256 And yes, since there were only 128 characters, the compiler wasn't able to think what to print in 129, and the loop got messy... Also, some ASCII characters are non-printable and control related, which may make the loop uncontrollable. These include DEL, NUL Start of Heading, End of Heading, Carriage Return and Escape Characters, Device Control Characters, etc. So, if the problem persists, print characters from 32-126 //Both included, as this range has all printable characters... Another thing is that Escape characters must be printed as strings, if you want them as well like - "\\t"...
10th Apr 2017, 2:26 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 8
@Krishna Teja Yeluripati Yes, sir , you're right and in Code::Blocks, this happened after 128 only...(It had the default as ASCII - 7)
10th Apr 2017, 4:26 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 7
When maximum value (of char) in incremented, it returns minimum​ value (of char). So, the loop condition never fails. Check this code. https://code.sololearn.com/cdsAkcwBrO8Y/?ref=app
10th Apr 2017, 2:06 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 7
@Aditya kumar pandey If you're right, tell me why this is not infinite: #include <iostream> using namespace std; int main() { for(char x=32; x<127; ++x) { cout <<x; } return 0; }
10th Apr 2017, 4:23 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 5
@ Chandra Shekhar G No Problem ^_^ !
10th Apr 2017, 9:32 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 1
thanks @kinshukVasisht
10th Apr 2017, 9:24 AM
Çhandra_Şhekar
Çhandra_Şhekar - avatar