How many times will this loop execute?
unsigned char half_limit = 150;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
// do something;
}
unsigned char half_limit = 150;
for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
// do something;
}
Transforming the comments into appropriate answer:
2*half_limit
results in 300
due to integer promotion (link is for C, but same rules apply for C++), however, this value cannot be stored in unsigned char
(i
!!!), which means that the loop variable never can reach it; instead, it will overflow when being 255 at ++i
and thus "restarts" with 0.
The result is an infinite loop (assuming the do something
part does not modify half_limit).
Side note 1: This applies for most common and ancient hardware, as these typically have eight bit wide char types. However, C++ standard's only (and just the same in C...) requirement for unsigned char is being able to minimally hold the values from 0 to 255 (and actually, not having larger size than unsigned short). Signed and unsigned char being larger than 8 bit is absolutely valid, and such hardware even exists (e. g. some DSP from TI with 16-bit char). On such hardware, the loop would have run 300 times!
Side note 2: If there are no visible side effects in the do something
part, the compiler is allowed to optimise the loop away entirely, so it might not be run at all; however, we have undefined behaviour in the endless loop case (refer to Jarod'sanswer)!
Conclustion: As long as we do not know the hardware we are running on, what the do something
part really contains and which compiler was used with which optimisation flags, we actually cannot tell anything at all...
in i < 2 * half_limit
, we have integer promotion: we compare so i
with 300
.
i
, as unsigned char
would never reach that limit.
Overflow of unsigned char
is well defined, and wrap around maximum value.
So the loop in infinite.
So unless // do something;
does any of:
the code would be Undefined Behavior (UB)