For loop with unsigned char gives unexpected behavior

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?

+4
source share
2 answers

C / C ++, if necessary, extends the capacity of bits. He called promotion type Integer .

half_limit * 2 300. CHAR_BIT == 8, i , 300, . , 255, if .

+2

. :

2 * half_limit

half_limit unsigned char, 2 - int. , half_limit int, 300.

i < 2 * half_limit

int, i int. .

++i , i - unsigned char, . 255 0, i < 2 * half_limit , i 300.

if (i <= 255), i 0 , .

+8

Source: https://habr.com/ru/post/1692462/


All Articles