Consider the following function
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
In order to exchange the values of two variables and .
View worked solution
Answer: D
In the C programming language, parameters are passed by value by default.
Let's analyze what happens when we try to use the given swap function:
- Call
swap(x, y): The values of the argumentsxandyare copied into the local parametersaandbof the function. Inside the function, the values ofaandbare successfully swapped, but these changes are local to the function's activation record. Once the function returns, the local variablesaandbare destroyed, and the original variablesxandyin the calling function remain completely unaffected. - Call
swap(&x, &y): This will result in a compilation error because the function signature isvoid swap(int a, int b), which expects integer values, not pointers (addresses) of typeint *.
Therefore, the given swap(x, y) function cannot be used to exchange the values of x and y because the parameters are passed by value.
Thus, Option D is the correct statement.
Free practice · Your answers on this page are not saved.
