Im practicing interview questions but am having a hard time with this basic question:
How many times will this loop execute?
unsigned char half_limit = 150;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
std::cout << i;
}
My thought is that since an unsigned int only reaches 255 it will execute forever since when I increment an unsigned char when it is at 255 it will revert back to 0? However this thinking is wrong and what is even more strange is that this is the output cout is giving me:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~���������������������������������������������������������������������������������������������������������������������������������
And when I try to limit the look with something like the following:
if (i <= 255)
std::cout << i;
else
break;
The loop is still infinite.
My questions is what is the expected result of the code and why is this the case?
This is an infinite loop. Let's take a step-by-step look:
2 * half_limit
half_limit
is unsigned char
but 2
is int
. So half_limit
is promoted to int
and the result is integer 300
.
i < 2 * half_limit
Since right hand size is int
, i
is also promoted to int
. There is no problem here.
But in ++i
no promotion is involved and i
is an unsigned char
as declared. So after reaching 255
it goes back to 0
and the condition i < 2 * half_limit
is always true as i
will never reach to 300
.
The situation is same for your second condition if (i <= 255)
as i
goes back to 0
before this check is made.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With