C++ define expression evaluation -


this question has answer here:

suppose have expression:

#define cube(x) x * x * x 

and call it:

int n = 3, v; v = cube(n + 1);   // v = 10 v = cube((n + 1)); // v = 64 v = cube(n);       // v = 27 

so question is: why first operation not make v = 64?

macros not evaluated (in sense of common interpretation of evaluation), expanded @ compile time.

before file compiled, there program called c preprocessor replaces macro invocation literally/textually , prepares file actual compilation, macro

#define cube(x) x * x * x when 

this

v = cube(n + 1); 

is replaced (expaned correct term)

v = n + 1 * n + 1 * n + 1; // simplifies v = n + n + n + 1; // , again v = 3 * n + 1; 

which n = 3 gives 10 observed result.

note, when add parentheses

v = cube((n + 1)); 

then, expansion is

v = (n + 1) * (n + 1) * (n + 1); 

which expect cube() do, prevent should redefine macro this

#define cube(x) ((x) * (x) * (x)) 

if using gcc try

gcc -e source.c 

and check result verify how macro expanded.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -