Understanding of the char type and understanding of the complement code. Understanding of the char type
I encountered such a small program today and thought it was easy to ignore some of the problems!
The program code is as follows:
The result of the program is:
I think a lot of white people like me may start to wonder why the final result is 255! First, we need to know that strlen () is a function used to calculate the string length, but why is the final String Length 255? Isn't there 1000 elements in the defined array a, and the for loop is also executed 999 times?
For char, we need to know that its implicit end mark is \ 0. When the compiler recognizes a char type variable and reads \ 0, it indicates the end. For this program, we also need to pay attention to the value range of char:-128 ~ 127
So when I = 128, a [128] =-1-128 =-129, the problem occurs here. The minimum value of the element in a can only be-128. What should I do? Here we need to know that in a computer, data is stored in the form of a complement,-128 encoding in the computer is 1000 0000, and-1 Completion code is 1111 1111, therefore, the complement code of-129 is 1 0111 1111, but the binary bit in char is only eight bits, so the highest bit is discarded. The rest is used as the complement code, that is, 0111 1111 (0x7f) through the loop, subtract one 0x7d, 0x7c, 0x7b, 0x7a, 0x79,0x78,0x77,0 x, 0x71, 0x70 ...... 0x00, so when the encoding is 0x00, a [255] = 0; so when a [255] = 0, as the string end sign, in a [0] ~ The elements of a [254] are not 0, so the final execution result is that the length of string a is 255.