By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,962 Members | 1,998 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,962 IT Pros & Developers. It's quick & easy.

C code with macros

P: 18
Hi ,all

#define MAX(x,y) ((x)>(y)?(x):(y)
main()
{
intx=5,y=5;
printf("maximum is %d",MAX(++x,++y));
}

this is a code using macros....
the output for this code is 6
is my answer right...

i hav a little bit confusion whether the maximum will be 6 or 5...
please clear my confusion..

Thanks in advance....
Aug 6 '07 #1
Share this Question
Share on Google+
7 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
The macro expands to:
Expand|Select|Wrap|Line Numbers
  1.  ((++x)>(++y)?(++x):(++y)
  2.  
x and y are altered multiple times before the end of the statement (called a sequence point). Changing a variable more than once within a given sequence point produces indeterminate results.

Therefore, any answer may be expected.
Aug 6 '07 #2

P: 6
Hey max value will increment two times so take a close look at the code by replacing the macro call by its body
Aug 7 '07 #3

P: 18
ok....i will try some more codes with macros..
Aug 7 '07 #4

P: 2
Answer I think is 7.
Because the result i.e ++y will be calculated twice.
Once during the comparision (++x > ++Y) and again during answering.
++x : ++y.
This sort of arguments should not be used in macros, as their answer cant be predicted easily and they may give unexpected results.

Thanks
Pradeep
Aug 9 '07 #5

weaknessforcats
Expert Mod 5K+
P: 9,197
Did anyone read my Post#2??
Aug 9 '07 #6

Expert 10K+
P: 11,448
Did anyone read my Post#2??
I did, but I wasn't participating in this thread ;-) You're right though: the OP should
be happy that no daemons flew out of his nose after doing such naughty deeds.

kind regards,

Jos
Aug 9 '07 #7

RRick
Expert 100+
P: 463
In this case, I think undefined means that no specific/single value can be expected. Are you going to get -23457898 as an answer? Probably not, but if you're expecting 7 you're going to be just as disappointed. What happens is compiler specific and that spells trouble.
Aug 9 '07 #8

Post your reply

Sign in to post your reply or Sign up for a free account.