16
void swap(int &first, int &second){
    int temp = first;
    first = second;
    second = temp;
}
int a=3,b=2;
swap(a,b);

The compiler complaints that void swap(int &first, int &second) has a syntax error. Why? Doesn't C support references?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user1128265
  • 2,891
  • 10
  • 29
  • 34

3 Answers3

27

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);
Sean
  • 3,002
  • 1
  • 26
  • 32
20

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;     \
}
Mysticial
  • 464,885
  • 45
  • 335
  • 332
-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; 
}
  • 1
    Should be `void swap(int* a, int* b)` to avoid the `warning: control reaches end of non-void function` (never hurts to check `if (*a != *b)` before swapping...) – David C. Rankin May 30 '17 at 05:06
  • 7
    Please, oh please, do not use this. Aside from having an incorrect return type, and being harder to read than the kind with a temporary variable, it's slower on almost every architecture. The only thing a third variable costs is a temporary register. – nmichaels Mar 15 '19 at 16:22