Professional Documents
Culture Documents
Functions
The Concept of Functions
Functions are the basic building blocks
of C++ programs
A function is a block of statements with
a given name, which can be treated as
a unit.
There are two main types of functions
in C++
Standard C++ library functions
Programmer-defined (user-defined)
functions
Anatomy of a Function
A function consists of six parts:
Return type
Function name Signature of the function
Argument list
Opening brace (start of function)
Function body
Closing brace (end of function)
Function Declaration
According to ANSI standard, the declaration of a
function specifies the interpretation and attributes of
the function
Function declaration
int addnumbers(int x, int y);
Function definition
int addnumbers(int x, int y){
int ans;
ans = x + y;
return ans;
}
Example 2: Square of a Number
Function declaration
int square(int x);
Function definition
int square(int x){
int ans;
ans = x * x;
return ans;
}
#include<iostream>
using namespace std;
/* Function declaration */
int addnumbers(int x, int y);
int main(){
int result;
result=addnumbers(5,12); /*Function call*/
cout<<result<<endl;
system("PAUSE");
return 0;
}
/* Function definition */
int addnumbers(int x, int y){
int ans;
ans=x+y;
return ans;
}
Return Types
A function can be declared to return any data type.
int main(){
char name[16];
cout<<"Enter your name: ";
cin>>name;
sayhi(name);
system("PAUSE");
return 0;
}
Making Function Calls
A function call is an expression that can be used as
a single statement or within other statements.
If the function returns a value then obtain the value and assign
it to a variable.
e.g. sum=addnumbers(5, 10);
cout<<addnumbers(5, 10)<<endl;