-1

I have idea about macro preprocessor directive.In below question how replacement in source code is done by compiler that it is giving output as "y is 392"

#include <stdio.h>
#define CUBE(x) (x*x*x)
void main(void)
{
     int x;
     int y;
     x = 5;
     y = CUBE(++x);
     printf("y is %d\n", y);
}

output:y is 392.

  • 2
    It's UB — undefined behaviour — because you end up with `y = (++x*++x*++x);` and you can't do multiple increments on a single variable between two sequence points (within a single assignment). Also, note too that the macro miscomputes the cube if used with `y = CUBE(x + 3);`. Use parentheses around arguments and around the expression — `#define CUBE(x) ((x)*(x)*(x))`. – Jonathan Leffler Feb 06 '18 at 15:18
  • It's an undefined operation. The macro expands to `(++x*++x*++x)`. – Mad Physicist Feb 06 '18 at 15:20

2 Answers2

1

The behaviour of your code is undefined.

CUBE(++x) expands to (++x * ++x * ++x): there are no sequencing points in that expression and it simultaneously reads and writes to x.

This epitomises why macros that do arithmetic are computationally lethal.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

The preprocessor is replacing that with

y = (++x*++x*++x);

Which is undefined behaviour.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Colin
  • 3,394
  • 1
  • 21
  • 29