Some explanations of integer range in C language

Time:2019-10-17

Sample code

#include 

int main() {
    
    char c = 255;
    printf("%d\n", c);
    int i = 255;
    printf("%d\n", i);

    return 0;
}

 

Output result

-1
255

 

explain

  Computers store values in the form of binary complements.

The size of char is 1 byte (8bit), and the value range is – 128 ~ 127. The binary source code of 255 is 1111111, and the value of 1111111 as complement code is – 1, so char c = 255 outputs – 1.It is assumed that char c = 257. The binary of 257 is (1) 0000 0001, the high-order 1 out of range is discarded, the sign bit 0 is a positive number, the complement of a positive number is itself, and the code result will output 1.

The size of int is 4 bytes (32bit), the value range is – 2 ^ 31 ~ 2 ^ 31 – 1, and its range value usually depends on the compiler (CPU). The binary source code of 255 is 0000 0000 0000 0000 0000 1111 11111, the range of int is far beyond the range of char, so int i = 255 outputs 255.