Nov. 23, 2021 c-programming Neeraj Shankar

Functions in C++

We can define function as a group of statements that together perform a task. Every C++ program has at least one function, which is main().


A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

 

Syntax:

//Function declaration - return type function_name(formal paramaters);
void swap(int x, int y);

Parameter names are not important in function declaration only their type is required, so following is also valid declaratio. 

void swap(int, int);

 

We can call a function by three ways:

1. Call By Value:

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. 

In this case, changes made to the parameter inside the function have no effect on the argument.

Here is an example program:

#include<iostream>
using namespace std;

//Function declaration and defination
void swap(int x, int y){
int temp;
temp = x ;
x = y;
y = temp;
}

//main method
int main(){

//local variable declaration
int a=100;
int b = 200;

//Printing the value of local variables before swapping
cout<<"The value of a before swap: "<<a<<endl;
cout<<"The value of b before swap:"<<b<<endl;

//calling the swap method
swap(a,b);

//Printing the value of local variables after swapping
//changes made to the parameter inside the function have no effect on the argument.
cout<<"The value of a after swap: "<<a<<endl;
cout<<"The value of b after swap:"<<b<<endl;

return 0;

}

Output:

The value of a before swap: 100
The value of b before swap:200
The value of a after swap: 100
The value of b after swap:200

Neeraj Shankar

A result-oriented professional with over 4 years’ experience under different job roles which includes over 2 year of experience with Software Engineer (as also a freelancer)

Comments

Leave a comment