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

macro usage - cpp faq example

P: n/a
Hi,
This example is taken from the cpp faq by Marshall Cline, section 9.5.

// A macro that returns the absolute value of i
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )

// An inline function that returns the absolute value of i
inline
int safe(int i)
{
return i >= 0 ? i : -i;
}

int f();

void userCode(int x)
{
int ans;

ans = unsafe(x++); // Error! x is incremented twice
ans = unsafe(f()); // Danger! f() is called twice

ans = safe(x++); // Correct! x is incremented once
ans = safe(f()); // Correct! f() is called once
}

My question: What is it that makes x get incremented twice in
ans = unsafe(x++) ?

Regards
आलोक
--
http://9211.blogspot.com
Can't see Hindi? http://geocities.com/alkuma/seehindi.html
http://groups.yahoo.com/group/linux-bangalore-hindi/
Discuss devanagari at http://groups.yahoo.com/group/devanaagarii/
alok_kumar ऍट softhome डॉट net
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
आलोक कुमार wrote:
Hi,
This example is taken from the cpp faq by Marshall Cline, section 9.5.

// A macro that returns the absolute value of i
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )

// An inline function that returns the absolute value of i
inline
int safe(int i)
{
return i >= 0 ? i : -i;
}

int f();

void userCode(int x)
{
int ans;

ans = unsafe(x++); // Error! x is incremented twice
ans = unsafe(f()); // Danger! f() is called twice

ans = safe(x++); // Correct! x is incremented once
ans = safe(f()); // Correct! f() is called once
}

My question: What is it that makes x get incremented twice in
ans = unsafe(x++) ?

Macro expansion in C++ (as inherited from C) is pure text substitution.
In the example here, `unsafe(x++)' gets expanded to:

( (x++) >= 0 ? (x++) : -(x++) )

See the problem?

HTH,
--ag

--
Artie Gold -- Austin, Texas

Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.