C:定义的行为返回错误的结果

标签 c user-defined-functions

<分区>

所以我明天要考试,我在做题时遇到了这个问题。

#define mul(x,y) (x * y)
#include <stdio.h>
#include <string.h>

int main()
{
    int x = 3;
    int y = 4;
    int z = 0;
    z = mul(x+1, y+1);
    printf("4 * 5 = %d \n", z);
    return 0;
}

我的问题是,为什么输出 8 而不是 20。 因为当我将 z= mul(x+1,y+1) 替换为 z= mul((x+1),(y+1)) 时,我得到了正确答案 20

最佳答案

#define mul(x,y) (x * y)实际上告诉预编译器,如果它找到字符串 mul(any pattern X, any pattern Y),它应该用 替换它>(任何模式 X * 任何模式 Y)

那么你的例子中有什么?

int x = 3;
int y = 4;
int z = 0;
z = mul(x+1, y+1);

mul 之后被替换,你得到

int x = 3;
int y = 4;
int z = 0;
z = x+1*y+1;

==> z = 3 + 1*4 + 1 = 8

最佳做法是用括号将每个宏参数括起来。在你的例子中(为了达到预期的结果)它应该是:

#define mul(x,y) ((x) * (y))

关于C:定义的行为返回错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43504466/

相关文章:

c++ - 嵌入式编程...一开始

c - 这个C声明代码有什么问题?

c++ - 将 C++ 函数导入 teradata

sql - 函数不返回预期值

c++ - 如何在netbeans中创建项目依赖(c/c++插件)

c - 从文件读取数据并通过管道将其发送到另一个进程时出错

c - 为什么我们使用 sizeof 使用 malloc ?

excel - 在 Excel 中求偏导数

scala - UnFlatten Dataframe 到特定结构

arrays - 为什么我的原始数组被改变了?