Unexpected output in c [duplicate]

2019-01-20 04:26发布

This question already has an answer here:

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;
}

标签: c output
4条回答
时光不老,我们不散
2楼-- · 2019-01-20 05:08

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楼-- · 2019-01-20 05:10

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.

查看更多
Animai°情兽
4楼-- · 2019-01-20 05:14

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.

查看更多
爷、活的狠高调
5楼-- · 2019-01-20 05:22

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))
查看更多
登录 后发表回答