-3

This programm returns a=25, but if I define the sqr(x) as (x*x) it returns a=11. Why does this happen?

#include <stdio.h>
#define sqr(x) ((x)*(x))
main (){
    int a,b=3;
    
    a=sqr(b+2);
    printf("a=%d\n",a);
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 4
    Becasue `b + 2 * b + 2` is not `(b + 2) * (b + 2)` – William Pursell Jun 28 '21 at 14:42
  • In C macros are expanded during preprocessing, so instead of calling `sqr` like you would generally call a function, the definition is first expanded to `((x)*(x))` and `x` is replaced with `(b + 2)` in this instance. – h0r53 Jun 28 '21 at 14:44
  • There *has* to be a dup for this, but I can't seem to find it. – dbush Jun 28 '21 at 14:50

2 Answers2

4

The difference is in the way the macro is expanded.

With the extra parenthesis, the preprocessor expands the expression sqr(b+2) to this:

((b+2)*(b+2))

Which the compiler then interprets as:

a = ((3+2)*(3+2))
  = (5*5)
  = 25

Without the extra parenthesis, the preprocessor expands the expression sqr(b+2) to this:

(b+2*b+2)

Which the compiler interprets as:

a = (3+2*3+2)
  = (3+(2*3)+2)
  = (3+6+2)
  = 11

The * (multiplication) operator has a higher precedence than the + (addition) operator.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

If the macro is defined like

#define sqr(x) ( x * x )

when in this macro extension

sqr(b+2);

after substituting x for b + 2 you will have

b + 2 * b + 2

It is not the same as

( b + 2 ) * ( b + 2 )

that you would have if the macro was defined like

#define sqr(x) ( ( x ) * ( x ) )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335