Out parameters in C

非 Y 不嫁゛ 提交于 2019-12-05 01:35:11

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;     \
}

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);

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