gpt4 book ai didi

c - 定义此C宏的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-02 05:48:57 26 4
gpt4 key购买 nike

#include <stdio.h>
#define ABS(a) (a) < 0 ? -(a) : (a)
int main(void)
{
printf("%d\n", ABS(-3) + 1);
return 0;
}

赫伯特·希尔尔德(Herbert Schildt)的书中的这段代码片段看起来像是将生成输出 4,但实际上会输出 3。为什么?

我如何解决它?

最佳答案

展开您的宏:

#define ABS(a)  (a) < 0 ? -(a) : (a)

printf("%d\n", ABS(-3) + 1);

printf("%d\n", (-3) < 0 ? -(-3) : (-3) + 1); // you can get this with **gcc -E source.c

printf("%d\n", (-3) < 0 ? 3 : -2); //read about precedence to understand this step.

printf("%d\n", 3);

这是为什么打印 3的分步说明。您需要使用适当的括号对其进行修复。

关于c - 定义此C宏的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31530325/

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