为何向char类型赋值256会触发编译警告,赋值255却不会,但二者均存在整数溢出?
Why does assigning 256 to
char trigger a warning but 255 doesn't? Let's break this down step by step, focusing on C++'s type rules and compiler warning logic:
Core Background
First, remember that C++ leaves the signedness of char as implementation-defined—it can behave like either signed char (range: -128 to 127 on 8-bit systems) or unsigned char (range: 0 to 255). The -Woverflow warning your compiler uses considers this flexibility when deciding whether to flag an assignment.
Example 2: char c = 255;
- 255 is exactly the maximum value for
unsigned char, which is a valid possible type forchar. Even if your compiler treatscharassigned char, 255 will wrap around to-1(via 8-bit modulo 256 arithmetic), and-1is within thesigned charrange. - Since there exists a valid
chartype (unsigned) that can hold 255 without overflow, the compiler doesn't trigger a-Woverflowwarning—it can't be certain the assignment is problematic across all valid C++ implementations.
Example 1: char c = 256;
- 256 exceeds the range of both
signed char(max 127) andunsigned char(max 255). No matter howcharis configured on your system, this value will overflow and wrap around to0(256 modulo 256 = 0). - The compiler can definitively confirm this assignment will cause an overflow regardless of implementation, so it emits the
-Woverflowwarning to alert you to the value change.
Why the output isn't 255 or 256?
This ties back to your compiler's default char type (most mainstream compilers like GCC/Clang on x86 use signed char):
- For
char c = 255;: The 8-bit binary11111111represents-1in two's complement (the standard for signed integers), sostatic_cast<int>(c)outputs-1. - For
char c = 256;: 256 wraps to0modulo 256, sostatic_cast<int>(c)outputs0.
If your compiler used unsigned char by default, Example 2 would output 255, but Example 1 would still output 0.
内容的提问来源于stack exchange,提问作者I'mNotAModerator
相关产品推荐
相关产品推荐

