#define mystery?

Go down

#define mystery?

Post by Maithreyi on Wed Mar 24, 2010 11:45 am

#define max(a, b) ((a) > (b) ?(a) : (b))
#include<iostream>
using namespace std;
int main()
{
int a =5; b=0;
cout<<max(++a, b);
}

Here a is incremented twice! Can somebody justify and explain why this happens in the case of preprocessor directive #define

Maithreyi

Posts : 76
Points : 142
Join date : 2010-03-03
Age : 30
Location : Haldia

View user profile

Back to top Go down

Re: #define mystery?

Post by Mahee on Thu Mar 25, 2010 11:49 am

Have u tried exec tis prog,
Its getting incremented only once....
avatar
Mahee

Posts : 29
Points : 233
Join date : 2010-03-03
Location : Haldia

View user profile

Back to top Go down

Re: #define mystery?

Post by Christopher on Thu Mar 25, 2010 12:48 pm

yes. 'a' is incremented only once.
avatar
Christopher
Admin

Posts : 240
Points : 429
Join date : 2010-02-26
Age : 30

View user profile http://unixcpp.forumotion.com

Back to top Go down

Re: #define mystery?

Post by Vineet_More on Thu Mar 25, 2010 12:50 pm

Its getting incremented once only!! try to execute it.

Vineet_More

Posts : 27
Points : 31
Join date : 2010-02-26

View user profile

Back to top Go down

Re: #define mystery?

Post by Maithreyi on Thu Mar 25, 2010 1:37 pm

#include<iostream>
#define max(a,b) ((a) > (b) ?(a) : (b))
int a =5,b=0;
int main()
{
std::cout<<"\n"<<a<<max(++a,b);
return 0;
}

Now,its incrementing twice! Why ?

Maithreyi

Posts : 76
Points : 142
Join date : 2010-03-03
Age : 30
Location : Haldia

View user profile

Back to top Go down

Re: #define mystery?

Post by Saradha Kannan on Fri Mar 26, 2010 5:02 pm

Hey i guess... every (a) is replaced as (++a).. so it wil get incremented once while checking and once when it gets to the true result...
so it gets incremented twice

Saradha Kannan

Posts : 25
Points : 25
Join date : 2010-03-04

View user profile

Back to top Go down

Re: #define mystery?

Post by Maithreyi on Fri Mar 26, 2010 6:08 pm

@ Saradha! Yes, each a is replaced by ++a and hence getting incremented twice.But why is der a difference in the code I posted first and the one I posted later.They are identical, except for the placement of the macro! Why is there a difference ?

Maithreyi

Posts : 76
Points : 142
Join date : 2010-03-03
Age : 30
Location : Haldia

View user profile

Back to top Go down

Re: #define mystery?

Post by mightyganesh on Fri Mar 26, 2010 7:25 pm

i am getting only single incrementation for both the codes u gave! i tried it using the gcc compiler in our unix login!
did u ppl tried using ECLIPSE?
avatar
mightyganesh

Posts : 53
Points : 92
Join date : 2010-02-26
Age : 30

View user profile http://ganeshguna.blogspot.com

Back to top Go down

Re: #define mystery?

Post by Sponsored content


Sponsored content


Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum