macro usage - cpp faq example

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • आलोक कुमार

    macro usage - cpp faq example

    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
    आलोक
    --

    Can't see Hindi? http://geocities.com/alkuma/seehindi.html
    Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!

    Discuss devanagari at http://groups.yahoo.com/group/devanaagarii/
    alok_kumar ऍट softhome डॉट net
  • Artie Gold

    #2
    Re: macro usage - cpp faq example

    आलोक कुमार wrote:[color=blue]
    > 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++) ?
    >[/color]
    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

    Comment

    Working...