+ 3

It does not work when the "&"s and "*"s are removed. Why?

It works like this: int x = 25; int y = 100; int temp; printf("x is %d, y is %d\n", x, y); temp = x; x = y; y = temp; printf("x is %d, y is %d\n", x, y); But the two numbers do not swap when: int 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; } int swap(int num1, int num2) { int temp; temp = num1; num1 = num2; num2 = temp; return(num1, num2); } And when I give prefix "*" to "num1" and "num2" and change "swap(x, y);" to "swap(&x, &y);", they swap again. Why is the pointer necessary in this condition?

21st Nov 2018, 3:58 AM
smallujk
2 Answers
+ 7
If you don't use a pointer or a reference to pass the values to the function,only a copy of the values is passed to it,meaning that even if you change the values in the function,nothing will happen to the originals.... If you use '*' or '&',you directly point to the memory address of the variable,so any changes made in the function will be made to the originals.
21st Nov 2018, 4:05 AM
Mensch
Mensch - avatar
0
(*) or (&) are necessary to make a call to function by reference with the address. Where as the other case which donot require these *,& are changes done with swap of memory locations but not to the specified original values.This is call by value case so swaping of values can't be visualized unless the function invoked or called by reference
1st Dec 2018, 2:26 AM
Kondeti Sowjanya
Kondeti Sowjanya - avatar