gpt4 book ai didi

c - 为什么 '\97' ascii 值等于 55

转载 作者:太空狗 更新时间:2023-10-29 15:45:55 26 4
gpt4 key购买 nike

就像C代码:

#include<stdio.h>

int main(void) {
char c = '\97';
printf("%d",c);
return 0;
}

结果是55,但我不明白如何计算它。我知道'\'后面是八进制数或十六进制数,97 是十六进制数吗?

最佳答案

\ 是八进制转义序列,但 9 不是有效的八进制数字,因此它没有将其解释为八进制,而是被解释为多字符常量 \91 其值是实现定义的。在没有任何警告标志的情况下,gcc 默认提供以下警告:

warning: unknown escape sequence: '\9' [enabled by default]
warning: multi-character character constant [-Wmultichar]
warning: overflow in implicit constant conversion [-Woverflow]

C99 标准草案 6.4.4.4 Character constants10 说(强调我的):

An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

例如gcc 实现记录在案here并且如下:

The compiler evaluates a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not (a slight change from versions 3.1 and earlier of GCC). If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored.

For example, 'ab' for a target with an 8-bit char would be interpreted as ‘(int) ((unsigned char) 'a' * 256 + (unsigned char) 'b')’, and '\234a' as ‘(int) ((unsigned char) '\234' * 256 + (unsigned char) 'a')’.

据我所知,这被解释为:

char c = ((unsigned char)'\71')*256 + '7' ;

结果为 55,这与上面的多字符常量实现一致,尽管将 \9 转换为 \71 不明显。

编辑

我后来意识到真正发生的事情是 \ 被删除了,所以 \9 -> 9,所以我们真正拥有的是:

c = ((unsigned char)'9')*256 + '7' ;

这似乎更合理,但仍然是武断的,我不清楚为什么这不是一个直接的错误。

更新

通过阅读 The Annotated C++ Reference Manual 我们发现,在 Classic C 和旧版本的 C++ 中,当反斜杠后面的字符未定义为转义序列时,它是相等的到字符的数值。 ARM 部分 2.5.2:

This differs from the interpretation by Classic C and early versions of C++, where the value of a sequence of a blackslash followed by a character in the source character set, if not defined as an escape sequence, was equal to the numeric value of the character. For example '\q' would be equal to 'q'.

关于c - 为什么 '\97' ascii 值等于 55,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19898307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com