I am still a novice. Can someone explain this to me? Why is the answer 5 instead of 4?
insertCode:#include<stdio.h> #define TWICE(x) 2*x main(){ printf("%d\n", TWICE(3-1)); }
I am still a novice. Can someone explain this to me? Why is the answer 5 instead of 4?
insertCode:#include<stdio.h> #define TWICE(x) 2*x main(){ printf("%d\n", TWICE(3-1)); }
TWICE(3-1) expands to 2*3-1
Now consider
#define TWICE(x) 2*(x)
TWICE(3-1) expands to 2*(3-1)
It's important to remember that macros are simple text replacements - nothing is evaluated until the expansion happens.
Last edited by whiteflags; 06-28-2016 at 07:20 PM.
Actually, that still evaluates to 4. Did you mean to say that it expands to 2*3-1, which is equal to 5?
Simple:
After preprocessor processing, leaving off "#include<stdio.h>"Code:#define TWICE(x) 2*x main(){ printf("%d\n", TWICE(3-1)); }
2 times 3 minus 1 is 5!Code:main(){ printf("%d\n", 2*3-1); }
Your code should look something like:
Please note the added parentheses around the second 'x' in the #define! The 'x' in the #define is just a textual placeholder.Code:#include<stdio.h> #define TWICE(x) 2 * (x) int main(void) { printf("%d\n", TWICE(3-1)); }
Even though the multiplicative operator * has a high precedence, it is not the highest possible, so it is advisable to group the entire expression using parentheses:
Otherwise, precedence problems may still be possible, e.g.,Code:#define TWICE(x) (2 * (x))
Code:#define TWICE(x) (x) * 2 /* ... */ printf("%d\n", (int)TWICE(2.6));
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)