Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

writing an expression with #define

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
I actually have two questions.
#define x(wal) cout<<(wal) //why do I also
have
to declare x as
variable?

Next question:Author of a book I'm reading says I shouldn't use macros that generate expressions and than gives an example:
#define max(x,y) x>y ? x:y
result=max(myval++,99);
Here It says myval is incremented twice and if I was using a function it would not be incremented twice.Well,I did also used this expresion in a function and it also was incremented twice.Can someone explain to me why is this?


thank you
 
First, I do not think you need to declare x as a variable.
#define x(wal) cout<<wal

and later
int h;
x(h);
will output h to cout, no need to re-declare x.

Second, the reason the variable x is inc'd twice is because
the define uses text replacement and plants &quot;x++&quot; whenever
&quot;X&quot; is declared in the #define statement, each such time causes x to be inc'd
 
Thank you for your replie.I guess you're right on the first one,but I still don't understand why variable x is also inc'd twice when I used that expresion in a function?
 
As seeker says ‘the define uses text replacement’, therefore
result=max(myval++,99);
becomes
result=myval++>99 ? myval++:99
in this example myval will in fact only be incremented once if it’s value is less than (or equal to) 99, otherwise it will be incremented twice.
 
Check that you are not using the define in the function. Where ever you use the define, whether in the main code or a function, the anomalous effect will be the same.

What the book is saying is to rather write a function to do the same thing, ie:
int max(int a, int b)
{
return( a>b ? a : b );
}

If this was to be called as result = max(myval++,99) the initial value of myval would be passed to the function. After myval has been passed it would then be incremented.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top