0

This is a simple program to find the square of a number using a macro name SQUARE with an argument x. I am comfortable with the output of i,j but the output of other variables was unexpected as k,m are prime numbers also the value of l,n do not match the output which I predicted. Please help for the same. Thank you in advance.

Output Screen Image Link

#include <stdio.h>
#define SQUARE(x) (x * x)

void main() {
    int a = 3;
    int i, j, k, l, m, n;
    i = SQUARE(a);
    j = SQUARE(a++);
    k = SQUARE(a + 1);
    l = SQUARE(++a);
    m = SQUARE(a + 2);
    n = SQUARE(a++);
    printf("\n i= %d", i);
    printf("\n j= %d", j);
    printf("\n k= %d", k);
    printf("\n l= %d", l);
    printf("\n m= %d", m);
    printf("\n n= %d", n);
}
iBug
  • 35,554
  • 7
  • 89
  • 134
yash gandhi
  • 45
  • 1
  • 5

1 Answers1

2

C macro does plain text replacement, so SQUARE(a++) is directly replaced with (a++ * a++) in the preprocessing phase, and that's why you get wrong results.

See the (partial) output of gcc -E <your code> and you'll know why:

void main() {
    int a = 3;
    int i, j, k, l, m, n;
    i = (a * a);
    j = (a++ * a++);
    k = (a + 1 * a + 1);
    l = (++a * ++a);
    m = (a + 2 * a + 2);
    n = (a++ * a++);
    printf("\n i= %d", i);
    printf("\n j= %d", j);
    printf("\n k= %d", k);
    printf("\n l= %d", l);
    printf("\n m= %d", m);
    printf("\n n= %d", n);
}

If you really need macro, don't put any expression that has side effects (like a++) in the macro "call", and also surround "variables" with an extra pair of parentheses:

#define SQUARE(x) ((x) * (x))

int a = 3, b;
...
b = a;
i = SQUARE(b);
b = a++;
j = SQUARE(b);
b = a + 1;
k = SQUARE(b);
b = ++a;
l = SQUARE(b);
b = a + 2;
m = SQUARE(b);
b = a++;
n = SQUARE(b);

In fact, as said above, you don't need b for i, k and m, as the expressions used to assign to those three variables don't introduce side effects. You need b, however, with j, l and n.

iBug
  • 35,554
  • 7
  • 89
  • 134