Swap Simulator
C
Easy
3 views
Problem Description
Create two functions - swapByValue() and swapByReference(). In main, test both on the same numbers. Explain why the first won't work and why the second will.
Official Solution
#include <stdio.h>
/* Call by value */
void swapByValue(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
printf("Inside swapByValue: a=%d, b=%dn", a, b);
}
/* Call by reference */
void swapByReference(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
printf("Inside swapByReference: a=%d, b=%dn", *a, *b);
}
int main() {
int x = 10, y = 20;
printf("Before swap:n");
printf("x=%d, y=%dnn", x, y);
swapByValue(x, y);
printf("nAfter swapByValue (in main):n");
printf("x=%d, y=%dnn", x, y);
swapByReference(&x, &y);
printf("nAfter swapByReference (in main):n");
printf("x=%d, y=%dn", x, y);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!