0

I defined a function using #define, but when I print out a simple result of an operation it gives me an unexpected result. Here is the code:

#include <stdio.h>

#define CUBE(x) (x * x * x)

int main() {
int m, n = 3;
m = CUBE(n + 1);
printf("%d %d", m, n--);
return 0;
}

The result printed is 10 and 3 and I can't understand why. Since it multiplies n by itself 3 times, and then adds 1, shouldn't the result be 28 and 3?

  • 1
    `#define` is a plain text replacement. Do this replacement on yoru code and then see what the code looks like – M.M Dec 18 '16 at 10:50
  • After learning everything there is to know about the preprocessor, you will know this: if you want to define a function, define a function, not a macro. –  Dec 18 '16 at 12:13

3 Answers3

1

You don't #define functions, you #define macros, and those are quite different from functions.

  1. They aren't called. They are expanded into the source code directly by the preprocessor, before the code is compiled by the compiler.

  2. They have pitfalls that one must be aware of. To name one, if you pass an expression with side effects to a macro the uses its parameter more than once, the side effects will occur more than once, and you may get wrong results.

  3. The substation is plain token substitution, so

    CUBE(n + 1)
    

    will be expand to this:

    (n + 1 * n + 1 * n + 1) 
    
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0
#define CUBE(x) ((x) * (x) * (x))

should give you the expected result.

In your, on preprocessing, x in CUBE(x) is replaced by 3+1 which gives you

(3+1 * 3+1 * 3+1) // this happens during pre-processing, not in run time

as macro is plain-text replacement.

which will be grouped like

(3+(1 * 3)+(1 * 3)+1)

giving you 10. For more complex cases, I suggest writing a function.

sjsam
  • 21,411
  • 5
  • 55
  • 102
0

As the previous answer already suggest, you are missing a pair of brackets, because the preprocessor basically does find and replace. So your version result in

m = n + 1 * n + 1 * n + 1

which evaluates to the result, you observed.

With

#define CUBE(x) ((x) * (x) * (x))

you will get the correct calculation of

m = (n + 1) * (n + 1) * (n + 1)
taskinoor
  • 45,586
  • 12
  • 116
  • 142