C++ functions
functions
• Block of code that runs when it is called
• Two types of functions
1. Standard library functions or predefined functions
2. User defined functions
• Function has two parts
1. Function declaration
2. Function defination
Function declaration & function
defination
Function declaration Function defination
Void display()
Return type
{
function_name(parameters);
cout<<“hello World”;
}
Function call:
Int main() Function call:
{ Int main()
{
…..
…..
Display(); //function call
Display(); //function call
}
Function Parameters
Parameter passing: a) Call by value b) Call by reference
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
void fun(int x)
void fun(int* ptr)
{
{
// definition of function *ptr = 30;
x = 30;
}
}
int main()
int main()
{
{
int x = 20;
int x = 20;
fun(&x);
fun(x);
cout << "x = " << x; cout << "x = " << x;
return 0; return 0;
}
}