Machine-translated by Google. Questions are authored in English.
Top

Discussion

Why is this loop wrong?

for (uint8_t i = 0; i < 300; i++) {
    work(i);
}

  • A.the counter can never reach 300 and the loop never ends
  • B.the counter should be signed for a comparison against a constant
  • C.the body is called 300 times rather than 256
  • D.the comparison is undefined because of integer promotion

Answer: A

Correct answer: the counter can never reach 300 and the loop never ends

A uint8_t holds 0 to 255, so after 255 it wraps to 0 and the condition remains true for ever. The comparison itself is well defined, since the counter is promoted to int; the fault is that the type cannot represent the bound, which is a common and hard-to-spot error in constrained code.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.