UNIT2 :
Introduction to functions in C+++
Adjectives of this unit
- What is functions?
- Advantages of functions?
- Type of functions?
- General Syntax of a Function.
- What is function overloading ?
T.SUB: Abdulmalik A Alsarori
Functions
Function is a group of statements that
together perform a task.
Every C++ program has at least
one function, which is main, and all the most
trivial programs can define additional
functions.
Function declaration tells the compiler about
a function's name, return type, and
parameters.
Function definition provides the actual body
of the function.
Advantages Of Functions
Support for modular programming.
Reduction in program size.
Code duplication is avoided.
Code reusability is provided.
Functions can be called repetitively.
A set of functions can be used to form
libraries.
Types Of Function
There are two type of function :
Built in functions :-
- part of compiler package.
- part of standard library made available by
compiler.
- can be used in any program by including
respective header file.
User defined functions:-
- Created by user or programmer.
- Created as per requirement of the program.
General Syntax of a Function
Syntax :
return_type function_name( parameter1 ... parameterN )
{
body of function
}
The “return type” indicates what kind of data this function
returns, if any. Example: int
Keyword “void” expressly states that this function does not
return any value. ( Some languages would call this a
“subroutine”. )
If the return type is omitted, some compilers may assume
some type. This is a bad idea.
Sample Function
int add( int a , int b )
{
int sum;
sum = a + b;
return sum;
}
Function prototype
A function prototype is a declaration of a
function that tells the program about the
type of value returned by the function,
name of function, number and type of
arguments.
Function call
Function call
Function categories
Function with no return value and no argument.
void add(void);
Function with arguments passed and no return
value. void add(int,int);
Function with no arguments but returns a value.
int add(void);
Function with arguments and returns a value.
int add(int,int);
Function will not return any value but passes argument
ii. Function will not return any value but passes
#include<iostream.h>
void add(int x,int y)
{
int c;
c=x+y;
cout<<“addition is”<<c;
}
int main()
{
int a,b;
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
return 0;
}