#define sqr(a) a*a
x = 100/sqr(5);

Answer: value of x will be 100

Surprised! Let us expand the macro in the statement and see how it happened.

x = 100 / 5 * 5;
x = (100 / 5) * 5; /*Division has higher precedence*/
x = 20 * 5;
x = 100;

The result will be as expected if while defining the macro, we enclose it in brackets like so

#define sqr(x) (a * a)

Expanding the line
x = 100 / (5 * 5);/*macro replacement*/
x = 100 / 25;
x = 4;

This happens because the C preprocessor replaces macro calls with the macro value as it is, rather than treating it as a pointer to a memory location like in function calls. Please be careful while dealing with macros in the future.

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

strcpy and strcat source, memcpy vs memmove, strrev source, strdup, strtok, macro definition, C exception handling, setjmp and longjmp,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan