gpt4 book ai didi

编写十六进制和十进制数的简单加法的约定

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

即使是老手,恐怕我(不再)完全掌握 C 中常量的解析。以下 1-liners 中的第二个无法编译:

int main( void ) { return (0xe +2); }
int main( void ) { return (0xe+2); }

$ gcc -s weird.c

weird.c: In function ‘main’:
weird.c:1:28: error: invalid suffix "+2" on integer constant
int main( void ) { return (0xe+2); }
^

编译失败的原因可能是根据 C11 标准条款 6.4.4.2 将 0xe+2 解析为十六进制浮点常量。我的问题是是否存在一个约定来在 C 中编写十六进制和十进制数字的简单加法,我不喜欢在解析时必须依赖空格。

这是 gcc 版本 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)。预处理后停止编译(-E)表明编译失败发生在gcc而不是cpp。

最佳答案

因为 GCC 认为 0xe+2 是一个 float ,而这只是两个整数的相加。

根据 cppreference :

Due to maximal munch, hexadecimal integer constants ending in e and E, when followed by the operators + or -, must be separated from the operator with whitespace or parentheses in the source:

int x = 0xE+2;   // error
int y = 0xa+2; // OK
int z = 0xE +2; // OK
int q = (0xE)+2; // OK

关于编写十六进制和十进制数的简单加法的约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49767819/

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