Loading your workspace…
Loading your workspace…
Read two integers and exchange their values using a temporary variable, through a function that receives pointers.
#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main(void) {
int a, b;
printf("Enter two integers:\n");
if (scanf("%d %d", &a, &b) != 2) {
printf("Error: invalid input\n");
return 1;
}
swap(&a, &b);
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Input
3 8Output
Enter two integers:
After swap: a = 8, b = 3Input
4 4Output
Enter two integers:
After swap: a = 4, b = 4A function receives copies of its arguments, so swapping two int parameters would change only the copies. Passing the addresses lets swap change a and b in main.
The temporary variable is needed because the first assignment overwrites one of the values. Without it both variables would end up holding the same number.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
3 8
Expected output
Enter two integers: After swap: a = 8, b = 3
4 4
Expected output
Enter two integers: After swap: a = 4, b = 4
C passes arguments by value, so only pointers give the function access to the caller's variables.
The first assignment would overwrite one value, and both variables would end up equal.
Yes, with XOR or with addition and subtraction, but those break for some cases such as aliasing the same variable.
The value stored at the address that x points to.
The address-of operator gives swap a pointer to a in main's memory.
Back to all RCU 21BCA1C1P lab programs.