CodesandTutorials
Home   Programming   Hardware   Networking
 
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.  

C Categories

Call by Value

« Previous Point - Passing & Returning Arguments Next Point - Call by Reference »

Definition

When we pass value of a variable as an argument from the caller function to the function definition, it is called as call by value or passing by value.

Description

  • Value of actual arguments are copied to the formal arguments.
  • Change in formal argument values doesn't affect the actual arguments ,as formal arguments are limited to the specific function body.
  • swap(a,b);   //caller function with actual arguments
    .
    .
    .
    swap(int x, int y)   //function definition with formal arguments
    {
    //function body
    }

When to use

When function does not need to alter the values of the original variables in the calling function or program.

Source code

  • #include <conio.h>
  • #include <stdio.h>
  • void main()
  • {
  • 	int a=1,b=2;
  • 	clrscr();
  • 	printf("\nOriginal values of a:%d, b:%d",a,b);
  • 	swap(a,b);
  • 	printf("\nAfter swaping the values of a:%d, b:%d",a,b);
  • 	getch();
  • }
  • swap(int x, int y)
  • {
  • 	int temp = x;
  • 	x=y;
  • 	y=temp;
  • 	printf("\nSwaped values in swap function a:%d, b:%d",x,y);
  • 	return 0;
  • }

Output

Original values of a:1, b:2
Swaped values in swap function a:2, b:1
After swaping the values of a:1, b:2

Program working steps

  • First 2 lines are preprocessor directives which include defintion of functions like clrscr(), printf() etc.
  • Void main function, from where the program execution starts.
  • Declaration of two variables a and b with integer data-type.
  • clrscr() fucntion to clear the screen like cls in windows and clear in linux.
  • Printing of original values a and b before swapping.
  • swap(a,b); caller function with two arguments a,b calls swap function written on line no.13.
  • So program control moves to line no.13 where values of a and b are copied into the declared variable x and y.
  • Variable temp is used for temporary storage to swap the values of x and y.
  • Swaped values in swap function of a and b are then printed and program control is transfered back to main function using return 0; statement.
  • After returning back to main function next line no.10 is executed printing the value of a and after swap.
  • getch() function to wait for user to exit from the program.
  • From output of the program you can analyze that the value changed in the swap function doesn't affects the value in the main function.

« Previous Point - Passing & Returning Arguments Next Point - Call by Reference »

Tip Box

Remember

Variable name of actual and formal arguments should not be same.


Advertisement

Rate Website
   

 


Terms of Use | Privacy Policy | Contact Us
CodesandTutorials © 2014 All Rights Reserved