1.

Name the different methods used for passing arguments to a function. Write the difference between them with examples.

Answer»

Methods of calling functions: 

Two types call by value and call by reference. 

1. Call by value: 

In call by value method the copy of the original value is passed to the function, if the function makes any change will not affect the original value. 

Example

#include<iostream.h>

#include<conio.h>

void swap(int a, int b)

{

int temp;

temp = a;

a =b;

b = temp;

}

main()

{

cirscr();

int a,b;

cout<<"Enter value for a and b:-";

cin>>a>>b;

{

cout<<"The value before swap a="<<a<<"and b="<<b;

swap(a,b);

cout<<"\n The value before swap a="<<a<<"and b="<<b;

getch();

}

2. Call by reference: 

In call by reference method the address of the original value is passed to the function, if the function makes any change will affect the original value. 

Example

#include<iostream.h>

#include<conio.h>

void swap(int& a, int& b)

{

int temp;

temp = a;

a =b;

b = temp;

}

main()

{

cirscr();

int a,b;

cout<<"Enter value for a and b:-";

cin>>a>>b;

cout<<"The value before swap a="<<a<<"and b="<<b;

swap(a,b);

cout<<"\n The value before swap a="<<a<<"and b="<<b;

getch();

}



Discussion

No Comment Found

Related InterviewSolutions