Unexpected output in c [duplicate]

大憨熊 提交于 2019-11-27 07:22:13

问题


I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.?

#include<stdio.h>
#define mult(a,b) a*b
int main()
{
    int x=4,y=5;
    printf("%d",mult(x+2,y-1));
    return 0;
}

回答1:


Use parentheses in the macro definition

#include<stdio.h>
#define mult(a,b) ((a)*(b))
int main()
{
    int x=4,y=5;
    printf("%d",mult(x+2,y-1));
    return 0;
}

This is because different arithmetic operators have different precedence levels. Hence always use parentheses while defining the macro.




回答2:


mult(x+2,y-1) expands to x +2 * y -1 that is equals to 4 + 2 * 5 -1 gives output: 13.

You might be expecting answer (4 + 2) * (5 -1) = 6 * 4 = 24. To make it expand like this you should write parenthesize macro as @H2Co3 also suggesting:

#define mult(a,b) ((a)*(b))

Read aslo: So, what's wrong with using macros? by Bjarne Stroustrup.




回答3:


This is because C macros are simple textual substitutions, the macro writer must be sure to insert parentheses around every macro variable when it is substituted, and around the macro expansion itself, to prevent the resulting expansion from taking on new meanings.

If you observe your program: mult(a, b) is defined as a * b

mult(x + 2, y - 1) = x + 2 * y - 1 = 4 + 2 * 5 - 1 = 4 + 10 - 1 = 13

The Correct way would be:

mult(a, b) ((a) * (b))



回答4:


Because it replaces the arguments literally:

mult(x+2,y-1) --> mult(4+2,5-1) --> 4 + 2*5 - 1 --> 13

Try changing the define to:

#define mult(a,b) (a)*(b)

In this case the result after pre-processing is this:

int main()
{
    int x=4,y=5;
    printf("%d",(x+2)*(y-1));
    return 0;
}

This will solve the problem but it's still not the best way to do it.

#define mult(a,b) ((a)*(b))

This version is considered as good practice because in other types of situation the first one would fail. See the bellow example:

#include<stdio.h>
#define add(a,b) (a)+(b)
int main()
{
    int x=4,y=5;
    printf("%d",add(x+2,y-1)*add(x+2,y-1));
    return 0;
}

In this case it would give an incorrect answer because it is translated by the pre-processor to the fallowing:

int main()
{
    int x=4,y=5;
    printf("%d",(x+2)+(y-1)*(x+2)+(y-1));
    return 0;
}

printing 34 instead of 100.
For the ((a)+(b)) version it would translate to:

int main()
{
    int x=4,y=5;
    printf("%d",((x+2)+(y-1))*((x+2)+(y-1)));
    return 0;
}

giving a correct answer.



来源:https://stackoverflow.com/questions/17552976/unexpected-output-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!