In: Computer Science
Create a void function named swap that accepts two int parameters and swaps their values. Provide a main function demonstrating a call to the swap function. Document the dataflow of the function.
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int x = 10, y = 20;
swap(x, y);
return 0;
}
When main() function calls swap() function, it passes values to the
swap() function.
So swap(10, 20) will be called and nothing will be swapped by
swap() function.
The values of x and y will be as it is after calling swap().
The swap() function actually receives values of x and y and just
swap those values from another memory
location where the main() function put before calling swap()
function.
If you look at the 32 bit assembly generated by the compiler, it
will be as follows by main() function,
sub ebp, 8 ; allocating local memory for x and y integers
mov dword[ebp - 4], 10 ; assign 10 value to x
mov dword[ebp - 8], 20 ; assign 20 value to y
push dword[ebp - 8] ; push value into stack as second parameter of
function swap()
push dword[ebp - 4] ; push value into stack as first parameter of
function swap()
call swap ; call swap function, when call is made,
system automatically store main() function return pointer
add esp, 8 ; restore pushed stack memory
as you can see from above assembly code, swap receives values
not addresses of x and y.
the swap function would be same as above assembly code, just
assigning values to each other, whose location
is on stack which will not reflect the actual values of integers x
and y as function returns.
To make the function swap() workable, it must accepts its
parameters as pointer to integers.