简体   繁体   English

无符号字符范围是 0 到 255

[英]Unsigned char range is 0 to 255

#include <iostream> 
using namespace std; 
int main() 
{ 
    unsigned char counter = 0; 
    for (counter = 0; counter <= 255; counter++) { 
        printf("%d ", counter); 
    } 
    return 0; 
} 

Correct Output is Infinite loop But I thought output is 0,1,...255 because unsigned char ranges from 0 to 255.when the counter becomes 256 then only it exceeds the range.正确的 Output 是无限循环但我认为 output 是 0,1,...255,因为无符号字符的范围从 0 到 255。当计数器变为 256 时,只有它超出范围。 but here our condition is counter <=255 Please clear my doubt但这里我们的条件是计数器 <=255 请清除我的疑问

Think about unsigned char as a Byte: 0 -> 0b00000000 1 -> 0b00000001... 255 -> 0b11111111将 unsigned char 视为一个字节:0 -> 0b00000000 1 -> 0b00000001... 255 -> 0b11111111

Then the next number is 0 because you can't have a 9th bit.然后下一个数字是 0,因为你不能有第 9 位。 So after 0b11111111 it's 0b00000000.所以在 0b11111111 之后是 0b00000000。

That's why it is an infinite loop, it will never reach 256 and will always stay between 0 and 255.这就是为什么它是一个无限循环,它永远不会达到 256,并且总是保持在 0 到 255 之间。

This will result in infinite loop because condition (counter <= 255) in if loop is always true .这将导致无限循环,因为if循环中的条件(counter <= 255)始终为true

There is no way for this condition to be false : variable counter can not contain values higher than 255.这种情况不可能为false :变量counter不能包含高于 255 的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM