开发者

Understanding preprocessor directives in this case?

#define swap(a,b,c)(int t;t=a;a=b;b=t;);
void main()
{
    int x=10,y=20;
    swap (x,y,int);
    printf("%d %d\n",x,y);
}

开发者_StackOverflow社区What is the output and why?


Better to re-write your macro like this:

#define swap(a, b, type) \
        do { \
                type t = a; \
                a = b; \
                b = t; \
        } while (0)


Based on the usage and on the fact that c is not used in the macro, it looks like there's a typo in the macro. Instead of using int, it should say c:

#define swap(a,b,c)(c t;t=a;a=b;b=t;);

In fact, while this "fix" will give you the general idea of the macro, it won't compile. Please see Peyman's answer which tells you how to write it correctly.

Basically, it looks like a way to swap two variables a,b of the type c.

In your case the output would be:

20 10

The way this swapping algorithm works is simple. Basically, you want to copy a into b and b into a. However, if you just copy b into a, you'll lose a, and you'll be stuck with two copies of b.

Instead of just copying b into a, you first save a copy of a into a temporary variable called t, then copy b into a, then copy t (which holds the original value of a) into b. When you're done, you can forget about t.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜