cparameterspass-by-referenceout-parameters

Out parameters in C


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?


Solution

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