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; }
6 Réponses
+ 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"...
+ 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)
+ 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
+ 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;
}
+ 5
@ Chandra Shekhar G
No Problem ^_^ !
+ 1
thanks @kinshukVasisht