I deal with interview questions, but I find it difficult to ask this basic question:
How many times will this cycle run?
unsigned char half_limit = 150;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
std::cout << i;
}
My thought is that since unsigned int reaches 255, it will execute forever, because when I increment the unsigned char, when it is 255, will it go back to 0? However, this thinking is wrong, and even stranger is that I get the output of cout:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
And when I try to limit the appearance to something like the following:
if (i <= 255)
std::cout << i;
else
break;
The cycle is still endless.
My questions are, what is the expected result of the code, and why is this so?
source
share