#include <iostream>
usingnamespace std;
void Swap(int *a , int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a=0;
int b=0;
cout<<"Please enter integer A: ";
cin>>a;
cout<<"Please enter integer B: ";
cin>>b;
cout<<endl;
cout<<"************Before Swap************\n";
cout<<"Value of A ="<<a<<endl;
cout<<"Value of B ="<<b<<endl;
Swap (&a , &b);
cout<<endl;
cout<<"************After Swap*************\n";
cout<<"Value of A ="<<a<<endl;
cout<<"Value of B ="<<b<<endl;
return 0;
}
Now if you look at the function "Swap", I have used "void Swap". Therefore it must not return any value to main function (only "int" returns a value (at least that's what my teacher has taught me)). But if you execute it, the values are swaped in main function! How come ? Can anyone tell me how its possible ?
The function Swap recieves two pointers to variables of type int, "a" and "b". Note that this is only a pointer, not an actual value. In other words, rather than copying the value to a temporary variable of type int, the function recieves the location in memory of the two variables. Then, the function proceeds to make the variable in memory pointed to by "a" swap with the variable in memory pointed to by "b". Note that rather than editing the pointers or a temporary value, it is editing the memory addresses themselves.
This means that in your main function, you have declared two variables, a and b. These are assigned a segment in memory, and that data is stored there. Then, when you call your "Swap" function, the values of a and b are swapped, due to you giving it the reference of the variables, as in their location in memory.
Hope this Helps!
P.S.
Just because I can't resist, there are many other types that can be returned apart from int, such as floats, bools, variable pointers, function pointers, references, structs, unions, classes, etc.
When you declared a and b varibales. The OS would allocate memory space equals sizeof(int)= 4bytes for each variables. Pointer a and b in Swap function work on address of a and b variales in main function, not a copy of values of a and b variable.
Then that Swap function replaces the addresses of a and b instead of values??
I think you were wrong. It't replaces values of memory addrress, not eplaces the addresses of a and b instead of values??
I don't know maybe.
But what have I learned that:-
When you pass addresses of the variables and the function takes the values from addresses, you need not to mention any return type.
But if you take the values themselves and also you are returning the processed value, you do need to mention the return type (because in that case you would use 'int').