输出C中的参数

use*_*265 10 c out parameter-passing

void swap(int &first, int &second){
    int temp = first;
    first = second;
    second = temp;
}
Run Code Online (Sandbox Code Playgroud)

//////

int a=3,b=2;
swap(a,b);
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,C编译器抱怨"void swap(int&first,int&second)"在"(/ {"之前有一个语法错误,如缺少"&".

我不明白为什么?C不支持此功能吗?

Sea*_*ean 21

C不支持通过引用传递; 这是一个C++功能.你必须改为通过指针.

void swap(int *first, int *second){
    int temp = *first;
    *first = *second;
    *second = temp;
}

int a=3,b=2;
swap(&a,&b);
Run Code Online (Sandbox Code Playgroud)


Mys*_*ial 17

C不支持通过引用传递.所以你需要使用指针来做你想要实现的目标:

void swap(int *first, int *second){
    int temp = *first;
    *first = *second;
    *second = temp;
}


int a=3,b=2;
swap(&a,&b);
Run Code Online (Sandbox Code Playgroud)

推荐这个:但我会添加它以保持完整性.

如果您的参数没有副作用,您可以使用宏.

#define swap(a,b){   \
    int _temp = (a); \
    (a) = _b;        \
    (b) = _temp;     \
}
Run Code Online (Sandbox Code Playgroud)