Function
5
Why use Function
• Function are used for divide a large code into
module, due to this we can easily debug and
maintain the code.
• E.g. if we write a calculator programs at that time
we can write every logic in a separate function [For
addition sum(), for subtraction sub()].
• Any function can be called many times.
• Code Re-usability
• Easily to debug the program.
• Code optimization: No need to write lot of code.
2
Function Definitions
• A function is a group of statements that together perform a specific
task.
• Every C++ program has at least one function,
which is main().
• Every function that is called in a program must be defined
somewhere (once only).
• The syntax is:
return_type
function_name(parameter)
{
function body;
} 3
Function Declarations
• A function declaration is the process to tell the compiler about a
function name.
• Then, the actual body of the function can be defined separately.
• The syntax is:
return_type
function_name(parameter);
4
The syntax is: function_name(); // or
variable=function_name(argument);
5
Example: sum() function Print out:
#include<iostream> Sum: 33
using namespace std;
void sum(); // declaring a
function
int a = 11, b = 22, c;
int main()
{
sum(); // calling the function
}
void sum() // defining the
function
{
c = a + b;
6
cout << "Sum: " << c;
Type of Function
• There are two type of function in C++
Language. They are:
– Library function
• Predefined in C++
• Cin, cout,sqrt,gets
– User defined function.
• Created by users
7
Function
Arguments
• If a function take any arguments, it must declare variables that
accept the values as a arguments.
• These variables are called the formal parameters of the
function.
8
Function without arguments and parameters
#include <iostream>
using namespace std;
// declaring a function, no parameters
void greet() {
cout << "Hello there!";
}
int main() {
// calling the function, no arguments
greet();
return 0; OUTPUT
} Hello there!
9
#include<iostream>
using namespace std; EXAMPLE FOR ARGUMENTS AND
int min(); // declaring a function PARAMETERS
int main()
{
int a= 100;
int b= 20;
int ret;
ret = min(a,b);//arguments
cout<<"Min is "<<ret<<endl;
}
int min(int num1,int num2) //function definition num1 and num2 are parameters
{
int result;//local variable
if(num1<num2) OUTPUT
Min is 20
result = num1;
else
result = num2;
return result;
} 10
Passing value or data to function
• There are two ways to pass value or data to function.
– call by value
– call by reference
• Call by value: In call by value, original value can not be changed or
modified.
• Call by reference: In call by reference, original value is changed or
modified because we pass a reference (an address).
11
Continued
The value of num1 and num2 are initialized to
variables a and b respectively. These a and b are called as
parameters or formal parameters. For example:
//Arguments
//Parameters
12
Return Statement
A function can return a single value to the calling program
using return statement. In the previous program, the value of
add is returned from user-defined function to the calling
program using statement below:
13
Example: Call by Value function
#include<iostream>
Using namespace std;
void swap(int a, int b){
int temp;
Print out:
temp = a;
a = b; Value of a: 111
Value of b: 222
b = temp;
}
void main(){
int a=111, b=222;
swap(a, b); // passing value to function
cout<<"Value of a: "<< a <<endl;
cout<<"Value of b: "<< b <<endl;
}
14
Example: Call by Reference function
#include<iostream>
Using namespace std;
void swap(int *a, int *b){
int temp;
Print out:
temp = *a;
*a = *b; Value of a: 222
Value of b: 111
*b = temp;
}
void main(){
int a=111, b=222;
swap(&a, &b); // passing value to function
cout<<"Value of a: "<< a <<endl;
cout<<"Value of b: "<< b <<endl;
}
15
Summary: Argument Passing
• Arguments passed by value and by reference.
For example:
When f() is called, val++ For example: int main(){
increments a local copy of the int i=1;
first actual argument, whereas int j=1;
ref++ increments the second f ( i , j );
actual argument. }
It will increment j but not i.
16
Continued
Difference Between Call by Value and Call by Reference.
call by Value call by Reference
This method copy original value into This method copy address of arguments
function as a arguments. into function as a arguments.
Changes made to the parameter inside Changes made to the parameter affect
the function have no effect on the the argument. Because address is used
argument. to access the actual argument.
Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
Note: By default, C++ uses call by value to pass arguments.
17
Inline Function
• A function can be defined inline.
• The inline directive can be included before a function declaration to
specify that the function to be compiled as code in the same point
where it is called.
Syntax: inline type name ( arguments ... ) {
instructions ...
• It }
is not necessary to include the inline keyword in the call, it is just
like the one for any other function.
18
Example: Inline function
#include<iostream>
Using namespace std;
inline void show()
show OUTPUT
{ Hello word
cout<<"Hello world";
}
void main()
{
show();
show // Call it like a normal function
}
19
Function Overloading
• Two or more functions having same name but different
argument(s) are known as overloaded functions.
• Here, all 4 functions are overloaded functions called “test”
because argument(s) passed to these functions are different.
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b)
• N.B., the return{type
} of all these 4 functions are not same.
Overloaded functions may or may not have different return type
but it should have different argument(s).
20
• Here, both functions have the same name,
the same type, and the same number of
arguments. Hence, the compiler will throw an
error.
double test(int a) { }
int test(int b) { } // ERROR CODE!!!
21
#include <iostream>
using namespace std;
// function with 2 parameters
void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}
// function with double type single parameter
void display(double var) {
cout << "Double number: " << var << endl;
}
// function with int type single parameter
void display(int var) {
cout << "Integer number: " << var << endl;
}
int main() {
int a = 5;
double b = 5.5;
// call function with int type parameter Integer number: 5
display(a); Float number: 5.5
// call function with double type parameter Integer number: 5 and double number: 5.5
display(b);
// call function with 2 parameters
display(a, b);
return 0;
} 22
23
Example: Passing string to a Function
#include <iostream> Print out:
using namespace std; string is: passing str1
void display(char *); char array is: passing
void display(string); str
int main(){
string str1 = "passing str1";
char str[] = "passing str";
display(str1);
display(str); void display(char s[]){
cout << "char array is: " << s <<
return 0; endl;
} }
void display(string s)
{
cout << "string is: " << s << endl;
} 24
Structure
Structure Definitions
• A structure is a set of diverse types of data with different lengths
grouped under a unique declaration.
• The syntax is:
struct model_name {
type1 element1;
type2 element2;
type3 element3;
.
.
} object_name;
model_name is a name for the model of the structure type.
object_name is a valid identifier (or identifiers) for structure objects.
Within key brackets { } the types and their names corresponding to the
elements that compose the structure are listed.
26
continued
• If the structure definition includes the
parameter model_name, that parameter
becomes a valid type name equivalent to the
structure.
• For example: struct products {
char name [35];
float price;
} ;
.
.
// declaring three objects of that
type
products apple;
products orange, melon; 27
Example
#include <iostream> cout << "Enter age: ";
using namespace std; cin >> p1.age;
cout << "Enter salary:
struct Person ";
{ cin >> p1.salary;
char name[50]; cout << "\nDisplay
int age; Info."
<< endl;
float salary;
cout << "Name: "
}; << p1.name
int main() << endl;
cout <<"Age: "
{
<< p1.age
Person p1; << endl;
cout << "Enter Name: "; cout << "Salary: "
<< p1.salary;
cin.get(p1.name, 50);
return 0; 28
}
Example
Person getData(Person p) {
#include <iostream> cout << "Enter Full name:
using namespace std; ";
cin.get(p.name, 50);
struct Person { cout << "Enter age: ";
char name[50]; cin >> p.age;
int age; cout << "Enter salary: ";
float salary; cin >> p.salary;
}; return p;
}
void displayData(Person p) {
Person getData(Person); cout << "\nDisplay
void Information."
displayData(Person);
int main() { << endl;
Person p; cout << "Name: " <<
p = getData(p); p.name
displayData(p); << endl;
return 0; cout <<"Age: " << p.age
} << endl;
cout << "Salary: " <<
29
p.salary
Structure and Function
• A structure variable can be passed to a function in similar way as
normal argument.
For example:
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
void displayData(Person); // Function
declaration
30
Continued
int main() {
Person p; Enter Full name: Abe Kebe
cout << "Enter Full name: "; Enter age: 20
Enter salary: 823.50
cin.get(p.name, 50);
cout << "Enter age: "; Displaying Information.
cin >> p.age; Name: Abe Kebe
cout << "Enter salary: "; Age: 20
Salary: 823.50
cin >> p.salary;
// Function call with structure variable as an
argument
displayData(p);
return 0;
}
void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary << endl;
}
31
Pointers to structures
• Like any other type, structures can be pointed by pointers.
• The rules are the same than for fundamental data types,
• The pointer must be declared as pointer to the structure:
For example:
struct products {
char name [35];
float price;
} ;
products a_product;
// a_product is an object of struct type products
products*
products p_product;
// p_product is a pointer to point to objects of
32
products
Example 3:
#include <iostream> cout << "Enter feet: ";
using namespace std; cin >> (*ptr).feet;
cout << "Enter inch: ";
struct Distance { cin >> (*ptr).inch;
int feet;
float inch; cout << "Displaying
information." << endl;
};
cout << "Distance = "
int main() << (*ptr).feet
{ << " feet "
Distance *ptr, << (*ptr).inch
<< " inches" << endl;
d;
ptr = &d; return 0;
}
33
Enumeration Definition
• An enumeration is a user-defined data type that consists of integral
constants. To define an enumeration, keyword enum is used.
• The syntax is:
34
Example
35
Example
36