Upload
harshita-chaurasiya
View
167
Download
1
Embed Size (px)
Citation preview
PROGRAM – SWAP TWO NUMBERS BY CALL BY VALUE
void swap(int x, int y) { int z; z = x; x = y; y = z; printf("Swapped values are a = %d and b = %d", x, y); } int main() { int a = 7, b = 4; printf("Original values are a = %d and b = %d", a, b); swap(a, b); }
EXPLANATION
int main()int a=7, b=4;
int main() It is main function. Execution starts from here
int a=7 int b=4 Variables declare and values are
given
EXPLANATION• printf("Original values are a = %d and b = %d", a, b);• This will print original values • Values as a=7 and b=4
• swap(a,b);
swap(a,b) This will call swap function
Swap function is called and a, b are parameters which are passed in the function. a=7 and b=4 are passed
EXPLANATION
swap(a,b)
void swap(int x, int y)
Call swap
Pass a and b as parameters in swap function i.e.
void swap(int x, int y).a is passed as x and b as y in
void swap(int x, int y)
Swap is performed
EXPLANATION
• void swap(int x, int y)• Function declaration • Simple swap function to swap 2 numbers
swap
int x int y
Function name
void returntype
parameters
EXPLANATION void swap(int x, int y) { int z; z = x; x = y; y = z; printf("Swapped values are a = %d and b = %d", x, y); }
int z Z is a variable of integer type
EXPLANATION
z = x; x = y; y = z;
z
x
y z
y
x=
=
=
Swap function
Here z is a variable and x and y are paramters which are passed in the void swap () function.
EXPLANATION
z = x; x = y; y = z;
z=x z=7
x=y x=4
y=7 y=z
Values swapped
EXPLANATION• printf("Swapped values are a = %d and b = %d", x, y); We get swapped values of given values .
Original values are a=7 and b=4Swapped values are a=4 and b=7
Output of program
CALL BY VALUE FLOW DIAGRAM
• Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (a, b) can be split into some assembly steps like-
• push value of b• push value of a• save return address• call function• Here one point to note is x and y are in stack. Value of a and b will be
copied to x and y. Inside swap() value of x and y will be interchanged but it will not affect a and b in the main(). Please note a and b are located at the context of main() whereas x and y located at the context of swap(). When swap() function returns, this context of x and y will be lost and it will again come back to the context of a and b.
CALL BY VALUE FLOW DIAGRAM
CALL BY VALUE EXPLANATION• When passing Parameters using Call by Value,xerox copy of original
parameters is created and passed in the called function.• Any update made inside the method won’t affect the original value of
variable in calling function
THANK YOU