通过宏函数进行循环排列

Circular Permutation Through Macro Function

在C中,我想创建这样一个宏函数,将第一个参数的内容放入第二个参数中,将第二个参数的内容放入第三个参数中,将第三个参数的内容放入第一个参数中。下面的代码没有宏:

void circ2 ( int *a, int *b, int *c ){
    int temp1;
    int temp2;
    int temp3;
    temp1 = *a;
    temp2 = *b;
    temp3 = *c; 
    *a = temp3;
    *b = temp1;
    *c = temp2;
    //printf( "%d\n%d\n%d\n", a, b, c );
}

int main(){
    int x;
    int y;
    int z;
    x = 1;
    y = 2;
    z = 3;

    //circ(a, b, c);
    circ(x, y, z);
    printf( "%d\n%d\n%d\n", x, y, z );
    return 0;
}

以及我尝试创建的宏函数:

#define temporary
#define temporary2
#define temporary3
#define circ(x, y, z) (x != y && x != z && y != z) ? temporary = x, temporary2 = y, temporary3 = z, y = temporary, z = temporary2, x = temporary3 : x, y, z

但我收到以下错误:

error: expected expression before ‘=’ token

我哪里出错了?

我怀疑是temporarytemporary2等未申报的问题。您可能希望让您的宏跨越多个语句,用分号分隔,而不是使用逗号运算符。

temporarytemporary2temporary3 已定义,但您尚未提供它们应该扩展到的值,因此宏扩展的结果将看起来像

(x != y && x != z && y != z) ? = x, = y, = z(等等)

如果您知道宏参数的类型为 int,您可以将宏扩展为代码块,如下所示:

#include <stdio.h>

#define circ(x,y,z) {int tmp=z; z=y; y=x; x=tmp; }

int main()
{
   int a=1, b=2, c=3;
   circ(a,b,c);
   printf("a=%d, b=%d, c=%d\n",a,b,c);
}

输出:

a=3, b=1, c=2

你的非宏代码中的一个小错误:circ() 的参数需要是指针。 (我试图编辑,但它在 6 个字符的限制下。)调用应该是:

    circ(&x, &y, &z); 

排列需要是可执行代码,但是不需要需要条件执行。尝试类似的东西:

#define circ3(x, y, z) {int circ3__temp__=x; x = y; y = z; z = circ3__temp___;}

这将生成代码来置换三个 int 值,在大括号块内有一个局部变量。代码是内联生成的,临时变量的古怪名称是为了不重复调用范围中使用的任何名称。

请注意,当与 iffor 等控制表达式语句一起使用时,这不会表现得像表达式。例如

if (condition)
    circ3(a,b,c); /* semicolon here causes problem */
else /* "else without if" error here is that problem */
    circ3(x,y,z);

因此,它不是 void 函数调用的完美替代品。你需要删除;在调用中,或在宏调用周围放置 {} 大括号。

当你写:

#define temporary

你是在对 C 预处理器说 "temporary" 已定义,必须用任何东西替换它。 所以当你写:

#define circ(x,y,z) (x != y && x != z && y != z) ? temporary = x, temporary2 = y, temporary3 = z, y = temporary, z = temporary2, x = temporary3 : x, y, z
circ(a,b,c)

预处理器将 circ(a,b,c) 替换为:

(a != b && a != c && b != c) ?  = x, = y, = z, y = , z = , x = : x, y, z

C 编译器不理解它。

希望这对您有所帮助:

#define circ(x, y, z) do{int w;w=z;z=y;y=x;x=w;}while(0)