'Infinite loop generator in C
I tried this code in C
unsigned char c= 150;
for (unsigned char i = 0; i < (2*c); ++i)
{
// do something;
}
The program never halts. Why?
Solution 1:[1]
The sizeof(unsigned char) is 1, (i.e. 8 bits), so the maximum value it can hold is (2^8 - 1) which is 255. Hence, unsigned char cannot hold values over 255, after which the count restarts from 0. In your case, the loop condition i < 300 is always true, because c resets to 0 once it reaches 255.
To understand why it resets to zero, see the binary representation of 255. 255 can be written in binary as
11111111
which is 8 bits. So far so good.
If you add 1 to it, then the value becomes
100000000
which is 9 bits. Since unsigned char can store only 1 byte (or 8 bits), the most significant bit 1 is discarded and only the least significant 8 bits get stored in the variable. As a result, 00000000 is what gets stored in c, thus making it 0 again.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
