4

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?

3
  • If I'm not mistaken, this should result in an infinite loop. Commented Jan 20, 2018 at 18:27
  • But note that "what makes this a good interview question?" is off-topic here. Commented Jan 20, 2018 at 18:30
  • "if (i <= 255)" is obviously always true since i is unsigned char. Commented Jan 20, 2018 at 18:42

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"and i is an unsigned int as declared" it's actually unsigned char. Small typo ;>
Good answer - and thank you for correcting the typo :)
2

C/C++ extends expression's bit capacity if necessary. It's called Integer type promotion.

According to these rules, half_limit * 2 is getting promoted to integer value of 300. Assuming CHAR_BIT == 8, i is a single octet, and therefore it will never reach value of 300, so the cycle will continue forever. Also, an unsigned octet is always less or equal than 255, so it's your if expression is redundant.

1 Comment

How does this address the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.