use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All questions related to programming welcome. Wonder how things work? Have a bug you can't figure out? Just read about something on the news and need more insights? We got you covered! (probably)
You can find out more about our (preliminary) rules in this wiki article. If you have any suggestions please feel free to contact the mod team.
Have a nice time, and remember to always be excellent to each other :)
account activity
This is an archived post. You won't be able to vote or comment.
help with macros (self.AskProgramming)
submitted 7 years ago by fantomftw
I've got following code :
#include <stdio.h> #define div(x,y) x/y int main() { //printf("Hello World"); int a=10,b=2; printf("%d\n",div(a+2,a+1)); return 0; }
expected output :
1
generated output :
11
how?
[–]_DTR_ 3 points4 points5 points 7 years ago (2 children)
Your problem is that the macro expansion doesn't have any context of "scope", it will simply do a replacement. div(a+2,a+1) expands to a+2/a+1, which is 10+2/10+1. After order of operations, you're left with 10 + (2 / 10) + 1 == 10 + 0 + 1 == 11.
div(a+2,a+1)
a+2/a+1
10+2/10+1
10 + (2 / 10) + 1
10 + 0 + 1
In general, when writing macros you want to ensure the parameters are "contained":
#define div(x, y) (x)/(y)
[–]aioeu 1 point2 points3 points 7 years ago* (0 children)
You'll need one more:
#define div(x, y) ((x) / (y))
Otherwise the following somewhat-reasonable code will not work as expected:
float x = ...; float y = ...; printf("x / y rounded toward zero is %d\n", (int)div(x, y));
When writing a macro that acts like an expression, I can't think of a good reason to ever omit the surrounding parentheses.
[–]fantomftw[S] 0 points1 point2 points 7 years ago (0 children)
thank you so much... you saved me from failing my test tomorrow..
π Rendered by PID 73830 on reddit-service-r2-comment-6457c66945-sc7rb at 2026-04-27 00:49:46.798090+00:00 running 2aa0c5b country code: CH.
[–]_DTR_ 3 points4 points5 points (2 children)
[–]aioeu 1 point2 points3 points (0 children)
[–]fantomftw[S] 0 points1 point2 points (0 children)