Out parameters in C

爱⌒轻易说出口 提交于 2019-12-22 03:45:04

问题


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

//////

int a=3,b=2;
swap(a,b);

In the above example, the C compiler complaints that "void swap(int &first, int &second)" has a syntax error like missing "&" before "( / {".

I don't understand why? Doesn't C support this feature?


回答1:


C doesn't support passing by reference. So you will need to use pointers to do what you are trying to achieve:

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


int a=3,b=2;
swap(&a,&b);

I do NOT recommend this: But I'll add it for completeness.

You can use a macro if your parameters have no side-effects.

#define swap(a,b){   \
    int _temp = (a); \
    (a) = _b;        \
    (b) = _temp;     \
}



回答2:


C doesn't support passing by reference; that's a C++ feature. You'll have to pass pointers instead.

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

int a=3,b=2;
swap(&a,&b);



回答3:


for integer swap you can use this method without a local variable:

int swap(int* a, int* b)
{
    *a -= *b;  
    *b += *a;  
    *a = *b - *a; 
}


来源:https://stackoverflow.com/questions/9144516/out-parameters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!