Block of statement or code is called a function.
Create new function in c++
#include<iostream>
#include<conio.h>
using namespace std;
// function prototype
void sum();
int main(){
sum();
getch();
return 0;
}
// function definition
void sum(){
int a,b,c;
cout<<"Enter two number:";
cin>>a>>b;
c=a+b;
cout<<"Sum:"<<c;
}
Passing parameter to the function and default arguments
#include<iostream>
#include<conio.h>
using namespace std;
void sum(int a=10, int b=20);
int main(){
sum();
sum(100, 200);
getch();
return 0;
}
void sum(int a, int b){
int c;
c=a+b;
cout<<"Sum:"<<c;
}
Call by reference
Call by reference mean we pass address of a variable instead of value of variable.
#include<iostream>
#include<conio.h>
using namespace std;
void change(int *a, int *b);
int main(){
int a,b;
a=10;
b=20;
cout<<"value of a"<<a<<", value of b is"<<b<<endl;
change(&a, &b);
cout<<"value of a"<<a<<", value of b is"<<b<<endl;
getch();
return 0;
}
void change(int *a, int *b){
cout<<"value of a"<<++*a<<", value of b is"<<++*b<<endl;
}
Inline function
Inline function is a function that expanded in a line when it is called.
#include<iostream>
#include<conio.h>
using namespace std;
void power(int a);
int main(){
cout<<"power of 2 is:"<<power(2)<<endl;
cout<<"power of 3 is:"<<power(3)<<endl;
cout<<"power of 4 is:"<<power(4)<<endl;
cout<<"power of 5 is:"<<power(5)<<endl;
getch();
return 0;
}
void power(int a){
return a*a;
}
Default arguments
When we call a parametrized function without any parameters then we want to assign a default value to the parameter.
#include<iostream>
#include<conio.h>
using namespace std;
int sum(int a=10, int b=0);
int main(){
cout<< sum()<<endl;
cout<< sum(10, 20)<<endl;
getch();
return 0;
}
int sum(int a, int b){
return a+b;
}