If you use the GCC compiler to execute the following program under Linux, what is the output result?
#include<stdio.h>
int main(){
char c=127;
printf("%d",++c);
printf("%d",++c);
return 0;
}
Just know that it involves type conversion, data truncation and filling. But don’t know the specific explanation?
Original question source: Several classic interview questions in C language under Linux
巴扎黑2017-06-26 11:01:02
The length of
char
is 1 byte, and most machines treat it as a signed number, so its representation range is [-128, 127]
(see "In-depth Understanding of Computer Systems" P27 ~P28). So, when you assign 127 to c
, you execute ++c
, which causes an overflow because it only has one byte.
represents 127 in the machine, and it turns into binary like this 01111111
. You can see that when you add 1, the result becomes 10000000
. Since within the computer, negative numbers are represented by two’s complement, So it becomes -128. Then ++c
, it’s -127.
As for the different types, they all behave the same inside the computer, which is a piece of memory. So type is not a limitation.
天蓬老师2017-06-26 11:01:02
This question tests the compiler
, not the language.
Define 3 variables:
char c; // 表示一个 ascii字符
signed char s_c; //有符号 1字节 整数
unsigned char u_c; //无符号 1字节 整数
In C language, when c participates in calculation, whether c is converted into s_c or u_c is decided by the compiler
.
gcc considers c to be signed, and subsequent calculations and outputs are processed as signed numbers.