A classic interview question in C language under Linux
过去多啦不再A梦
过去多啦不再A梦 2017-06-26 10:59:02
0
2
1043

If you use the GCC compiler to execute the following program under Linux, what is the output result?

#include 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

过去多啦不再A梦
过去多啦不再A梦

reply all (2)
巴扎黑

The length of

charis 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 toc, you execute++c, which causes an overflow because it only has one byte.

represents 127 in the machine, and it turns into binary like this01111111. You can see that when you add 1, the result becomes10000000. 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.

    Peter_Zhu

    This question tests thecompiler, 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 thecompiler.

    gcc considers c to be signed, and subsequent calculations and outputs are processed as signed numbers.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!