c - 解释 C 中的反斜杠

标签 c escaping backslash slash

任何人都可以解释下面的代码,并请解释反斜杠 ( \ ) 在这种情况下的作用。还有什么 \' , \" , \ooo , \\ , \? 是什么意思?

#include <stdio.h>
int main(){
    char a = '\010';
    char y = '010';
    printf("%d,%d",a,y);

    return 0;
}

输出:8,48

最佳答案

'\010'是一个八进制转义序列 10八进制是 8十进制,它将被提升为 int打电话时 printf这样就解释了这个值。

'010'是一个多字符常量,它的值是实现定义的,如果我们看一下 C99 草案标准部分 6.4.4.4 字符常量 10 段说(强调我的):

[...]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你至少会看到这个警告:

warning: multi-character character constant [-Wmultichar]

可能还有关于溢出的警告:

warning: overflow in implicit constant conversion [-Woverflow]

y 的值obtains 更有趣一点,因为字符常量 有一个整数值,它不能只取第一个字符,多字符常量 必须取一个整数 值,然后转换为 charclang有助于提供更详细的警告:

warning: implicit conversion from 'int' to 'char' changes value from 3158320 to 48 [-Wconstant-conversion]

和当前版本的gcc产生相同的值,正如我们可以从这段简单的代码中看到的那样:

printf("%d\n",'010');

那么3158320在哪里呢?来自?对于 gcc至少,如果我们查看 Implementation-defined behavior 的文档它说:

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.

如果我们执行上面的操作(假设 8 位字符)文档,我们会看到:

 48*2^16 + 49*2^8 + 48  = 3158320
 ^         ^
 |         decimal value of ASCII '1'
 decimal value of ASCII '0'

gcc将转换 intchar使用模数 2^8不管是否charsignedunsigned 这实际上给我们留下了最后一个 8位或 48 .

关于c - 解释 C 中的反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19493974/

相关文章:

c - 在 C 中操作链表

jquery - 将 Java 中的 HTML 存储到 MYSQL 数据库中

bash - 引号转义——来自 bash 的 rsync

c - 以下 C 程序的输出是什么以及如何输出?

c - 没有系统 API 的 ansi 字符串到宽字符串

c - 将 C 中的文件打印到标准输出的最有效方法是什么?

c - 是否可以使用 32 位编译器实现 64 位整数?

Java 用反斜杠替换全部

Javascript:用双反斜杠替换反斜杠

php - 处理 JavaScript、PHP 和 MSSQL 中的反斜杠