问题
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