0

Why is temp used in this?

#include <stdio.h> void swap (int *num1, int *num2); int main() { int x = 25; int y = 100; printf("x is %d, y is %d\n", x, y); swap(&x, &y); printf("x is %d, y is %d\n", x, y); return 0; } void swap (int *num1, int *num2) { int temp; temp = *num1; *num1 = *num2; *num2 = temp; }

27th Dec 2019, 5:06 AM
SAzidsukc
SAzidsukc - avatar
2 ответов
+ 2
It is a temporary variable which is just used for swapping two values but is not required later.
27th Dec 2019, 5:35 AM
Avinesh
Avinesh - avatar
0
Try what happens without using "temp": *num1 = *num2; // ok, num1 has now the value of num2 *num2 = ???; // ooops, we have overwritten the previous value of num1
27th Dec 2019, 7:07 AM
Bilbo Baggins
Bilbo Baggins - avatar