Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

macros

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.

like image 887
maddy Avatar asked Jan 22 '10 04:01

maddy


2 Answers

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).

like image 200
James McNellis Avatar answered Oct 06 '22 20:10

James McNellis


Because of operator precedence 27/3*3*3 = 81

You could use instead:

inline int cube(int p) { return p*p*p; }
like image 38
stefanB Avatar answered Oct 06 '22 18:10

stefanB