Function In C++

C++ Function

Function in C++ : Function is defined as block of code which is used to perform a specific task. It can run only when we call it by its name in main function.

Syntax for creating function in c++:

void function_name()
{
statement 1;
statement 2;
}

Example :

#include <iostream.h>
void sum(int a , int b)
{
return a+b;
}
int main()
{
int x,y;
cout<<”Enter a number”<<endl;
cin>>x;
cout<<”Enter another number<endl;
cin>>y;
cout<<sum(x,y);
return 0;
}

Output :

Enter a number 5
Enter another number 4
9

Inline Function in C++:

An inline function is a function that is expanded in line when it is invoked. Inline expansion makes a program run faster because the overhead of a function call and return is eliminated. It is defined by using key word [inline].

Syntax for creating an inline function:

Inline function_name()
{
function body;
}

Example :

# include <iostream.h>
inline int sum(int a, int y)
{
return a+b;
}
inline int mul(int a, int b)
{
return b*a;
}
int main()
{
int a=3;
int b = 4;
cout<<sum(a,b);
cout<<mul(a,b);
return 0;
}

Output:

7
12

Properties of Inline Function:

1.Inline function sends request but not a command to compiler.
2.Compiler my serve or ignore the request.
3.if function has too many lines of code or if it has complicated logic then it is executed as normal function.


1 thought on “Function In C++”

  1. Pingback: Access Specifier in C++ - AskAtul.com

Leave a Comment

Your email address will not be published. Required fields are marked *