此C代码如何工作。我得到56作为\ 08的输出

Shi*_*agi 2 c

此代码的输出是56。

//输出:56

#include <stdio.h>

int main() {
    char c = '\08';
    printf("%d",c);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 6

正如@stark所评论的那样,您的常量由2个字节“ \ 0”和“ 8”组成。存储在变量中时,它们将被截断为'8' c。

在ASCII字符表中,您可以看到8以ASCII表示56,这是因为您使用%d格式说明符进行打印的:

在此处输入图片说明

如果您注意自己的警告,可能会发现自己:

main.c:4:14: warning: multi-character character constant [-Wmultichar]
    4 |     char c = '\08';
      | 
Run Code Online (Sandbox Code Playgroud)

此外,我建议您尝试这样打印:

printf("%c", c);
Run Code Online (Sandbox Code Playgroud)

然后输出将是:

8

它向您显示什么真正存储在变量中c。


提示:如果使用char c = '\01';或char c = '\07';以及介于两者之间的任何内容,则不会看到警告,并且不会打印相应的数字,因为这些是有效的八位数字,就像@Gerhardh的答案中提到的那样。