Consider the following C program.
# include <stdio.h>
void mystery (int *ptra, int *ptrb) {
int *temp;
temp = ptrb;
ptrb =ptra;
ptra = temp;
}
int main () {
int a = 2016, b=0, c= 4, d = 42;
mystery (&a, &b);
if (a < c)
mystery (&c, &a);
mystery (&a, &d);
printf("%d\n", a);
}
The output of the program is _________.
View worked solution
Answer: 2016
In C, arguments are passed by value. When pointers are passed to a function, the function receives copies of those pointers.
Inside the mystery function, the local pointer variables ptra and ptrb are swapped. This swap only affects these local copies and does not modify the values pointed to (i.e., *ptra and *ptrb are untouched), nor does it affect the variables in the calling function main.
Therefore, any call to mystery has no side effects on the variables in main. Their values remain unchanged throughout the execution:
- Initially,
a = 2016. - After
mystery(&a, &b),ais still2016. - The condition
a < c(i.e.,2016 < 4) is false, so the innermysterycall is not executed. - After
mystery(&a, &d),aremains2016.
Thus, printf("%d", a) prints 2016.
Free practice · Your answers on this page are not saved.
