Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
user1128265 Avatar asked Feb 04 '12 21:02

user1128265


People also ask

What are out parameters in C?

+ A[n-1] int sum(const int* A, const int n) { int result = 0; for(int i = 0; i < n; i++) { result += A[i]; } return result; } Out-parameters. An out-parameter represents information that is passed from the function back to its caller. The function accomplishes that by storing a value into that parameter.

What is an out parameter?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

What is input and output parameters in C?

C doesn't actually have "input" and "output" parameters, at least not directly. (Some languages do.) All arguments are passed by value, meaning that the function gets the value of the argument, but any modifications to the parameter are invisible to the caller.

What is in parameter and out parameter?

The in, ref, and out Modifiersref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.


2 Answers

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);
like image 132
Sean Avatar answered Oct 26 '22 21:10

Sean


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;     \
}
like image 33
Mysticial Avatar answered Oct 26 '22 20:10

Mysticial