0

Suppose we have this expression:

#define cube(x) x * x * x

And then we call it:

int n = 3, v;
v = cube(n + 1);   // v = 10
v = cube((n + 1)); // v = 64
v = cube(n);       // v = 27

So the question is: why first operation do not make v = 64?

Biffen
  • 6,249
  • 6
  • 28
  • 36
tomab
  • 2,061
  • 5
  • 27
  • 38

1 Answers1

14

Macros are not evaluated (in the sense of the common interpretation of evaluation), they are expanded at compile time.

Before the file is compiled, there is another program called the C Preprocessor that replaces the macro invocation literally/textually and prepares the file for actual compilation, so for your macro

#define cube(x) x * x * x when you do this

This

v = cube(n + 1);

is replaced with this (expaned is the correct term)

v = n + 1 * n + 1 * n + 1;
// Simplifies to
v = n + n + n + 1;
// and again
v = 3 * n + 1;

which for n = 3 gives you 10 exactly the observed result.

Note, that when you add parentheses

v = cube((n + 1));

then, the expansion is

v = (n + 1) * (n + 1) * (n + 1);

which is what you would expect cube() to do, so prevent this you should redefine your macro like this

#define cube(x) ((x) * (x) * (x))

If you are using gcc try

gcc -E source.c

and check the result to verify how the macro was expanded.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • @iharob: good answer. You might add a warning about potential problems with multiple evaluation. – chqrlie Jan 27 '16 at 14:00
  • 3
    @tomab, this is pure text substitution, which will surprise you further if you try to expand the macro with something that has side effects. – StoryTeller - Unslander Monica Jan 27 '16 at 14:00
  • Just a nitpick: macro/textual expansion *is* a form of evaluation, although it’s not the form most people are thinking of (and, importantly, it’s no an evaluation according to C++’s rules, nor those of conventional algebra). – Konrad Rudolph Jan 27 '16 at 14:26