c question - macros!?

consider the following:

#define SQR(x) x * x

printf("%d", 225/SQR(15)); /* Output is: 225 */ why?

Note: Both of the following result in output of 1

#define SQR(15) (x * x)

printf("%d", 225/SQR(15));

#define SQR(15) x * x

printf("%d", 225/(SQR(15)));

2 Answers

Relevance
  • 1 decade ago
    Favourite answer

    Because of the way the macro is expanded by the C pre-processor. The line

    printf("%d", 225/SQR(15));

    is expanded this way: printf("%d", 225/ 15 * 15 );

    while the lines (which probably should also define SQR(x))

    #define SQR(15) (x * x)

    printf("%d", 225/SQR(15));

    are expanded to

    #define SQR(15) (x * x)

    printf("%d", 225/ ( 15 * 15 ) );

    and

    #define SQR(15) x * x

    printf("%d", 225/(SQR(15)));

    is expanded to

    #define SQR(15) x * x

    printf("%d", 225/( 15 * 15));

    See the difference in calculations?

    Hope that helps.

    PS: The moral is to always enclose macro definitions in parentheses to prevent syntax scanning errors.

  • Paul
    Lv 7
    1 decade ago

    You really need to write the macro like this:

    #define SQR(x) ((x) * (x))

    Even with this definition though you can still run into problems (e.g. try it with SQR(x++)).

    Another good reason to use inline functions rather than macros.

Still have questions? Get answers by asking now.