Hello,
Im novice in programming, i made a search on it but i couldnt understand why this code outputs 8?
Code:#include <stdio.h> #define Z 7 + 3 int main (void){ int a = Z / 2; printf("%d", a); }
Hello,
Im novice in programming, i made a search on it but i couldnt understand why this code outputs 8?
Code:#include <stdio.h> #define Z 7 + 3 int main (void){ int a = Z / 2; printf("%d", a); }
You see, your Z just expands to 7 + 3Code:$ gcc -E foo.c <<< snipped a lot of expanded stdio.h int main (void){ int a = 7 + 3 / 2; printf("%d", a); }
Then operator precedence takes over.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
That's cool, so do not evaluate first like me Thank you a lot.
Your takeaway here should actually be that parentheses should be used for such macros, e.g.,
though of course in this specific case you might just write:Code:#define Z (7 + 3)
Code:#define Z 10
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)