Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c - Using macro results in incorrect output when used as part of a larger math expression - why does this happen?

This is a normal C routine program which i found out in some question bank. It is shown below:

#define CUBE(p) p*p*p

main()
{
    int k;
    k = 27 / CUBE(3);
    printf("%d", k);
}

As per my understanding and knowledge the value of K should be 1 as CUBE(3) would be replaced by 3*3*3 during preprocessing and after the subsequent compilation it would be giving the value of 1, but instead it has shown the value of 81 which has made me curious to know how it happened.

Can anyone please justify the answer of 81 to this question above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The preprocessor merely substitutes

CUBE(3)

with

3*3*3

So you end up with:

k=27/3*3*3

Which, evaluated left-to-right with operator precedence, is in fact 81.

If you add parenthesees around the macro, you should find the results are correct:

#define CUBE(p) (p*p*p)

It would be even better to surround each instance of p with parenthesees as well, as in:

#define CUBE(p) ((p)*(p)*(p))

Which will allow you to pass expressions to the macro correctly (for example, 1 + 2).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...