Function Calling in C++ :

Accessing or Calling a Function :

A function is called by providing the function name. When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it's return statement is executed or when its function ending or closing brace is reached, it returns program control back to the main program.

Function Arguments :

If a function is to use arguments, it must declare variables that accept the values of the arguments. While calling a function there are two ways that arguments can be passed to a function :

Call by Value :

The call by value method copies the values of actual parameters into the formal parameters, that is, the function creates its own copy of argument values and then uses them so, explain this in one simple example :

int main(){
int cube(int);
int vol,side=7;
vol = cube(side)
cout<<vol;}

int cube(int a){
return a*a*a;}


Output : 343


The main benefit of call by value method is that you cannot alter the variables that are used to call the function because any change that occurs inside function is on the functions copy of the argument value.

Call by Reference :

The call by reference method uses a different mechanism. In place of passing a value to the function being called , a reference to the original variable is passed so, explain again this in one another simple example :

int main{
void change(int &);
int a=4;
cout<< " a = "<<a;
change(a);
cout<< "\ta = "<<a;}

void change(int &z){z=10;
cout<< "\ta = "<<z;}


Output : a=4 a=10 a=10


Now, here a value is changed by change() function and set the address 4 to 10.


Returning From a Function :

A function terminates when either a return statement is encountered or the last statement in the function is executed. Generally, a return statement is used to terminate a function whether or not it returns a value.

The return Statement :

The return statement is useful in two ways. First, an immediate exit from the function is caused as soon as a return statement is encountered and the control passes back to the operating system which is mains caller. Second use of return a value to the calling code.

Example :

  1. /* Description: write a simple function program use return in C++ language */
  2. #include<iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. int retrn(int);
  7. int a,c;
  8. cout<< "press only a number under 1 or 2 : ";
  9. cin>>a;
  10. c=retrn(a);
  11. cout<<"you pressed : " <<c;
  12. }
  13. int retrn(int x)
  14. {
  15. int rtme=0;
  16. if(x==1) {
  17. rtme = 1;
  18. }
  19. else {
  20. rtme = 2;
  21. }
  22. return rtme;
  23. }

Output :

C++ language write a simple function program use return

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes