易百教程

78、如何在C语言中定义多行宏?

请参阅下面的示例,其中交换两个变量的值。

#include <stdio.h>
#define swap(x,y,T) do { \
    T temp = (*x);\
    (*x) = (*y); \
    (*y) = temp; \
} while (0)
int main(void)
{
    int a = 5;
    int b = 9;
    printf("Value of a and b before swaping\n");
    printf("a = %d\n",a);
    printf("b = %d\n",b);
    //Swap the number
    swap(&a,&b,int);
    printf("\nValue of a and b After swaping\n");
    printf("a = %d\n",a);
    printf("b = %d\n",b);
    return 0;
}