gpt4 book ai didi

c - 字符常量中的多个字符

转载 作者:太空狗 更新时间:2023-10-29 16:42:43 25 4
gpt4 key购买 nike

Some C compilers permit multiple characters in a character constant. This means that writing 'yes' instead of "yes" may well go undetected. Source: C traps and pitfalls

任何人都可以举一个字符常量中允许多个字符的例子吗?

最佳答案

正如 Code Monkey 所引用的那样,它是由实现定义的并且实现各不相同——这不仅仅是 BigEndian/LittleEndian 和字符集的差异。我已经用程序测试了四种实现(全部使用 ASCII)

#include <stdio.h>

int main()
{
unsigned value = 'ABCD';
char* ptr = (char*)&value;

printf("'ABCD' = %02x%02x%02x%02x = %08x\n", ptr[0], ptr[1], ptr[2], ptr[3], value);
value = 'ABC';
printf("'ABC' = %02x%02x%02x%02x = %08x\n", ptr[0], ptr[1], ptr[2], ptr[3], value);
return 0;
}

我得到了四个不同的结果

大端(AIX、POWER、IBM 编译器)

'ABCD' = 41424344 = 41424344
'ABC' = 00414243 = 00414243

大端(Solaris、Sparc、SUN 编译器)

'ABCD' = 44434241 = 44434241
'ABC' = 00434241 = 00434241

小端(Linux、x86_64、gcc)

'ABCD' = 44434241 = 41424344
'ABC' = 43424100 = 00414243

小端(Solaris、x86_64、Sun 编译器)

'ABCD' = 41424344 = 44434241
'ABC' = 41424300 = 00434241

关于c - 字符常量中的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944730/

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