SlideShare a Scribd company logo
FUNCTIONS
In C++
Introduction
• Functions are the main tool of Structured Programming.
• Functions decrease the size of program by calling the function at different
places in the program.
See the Syntax in C:
void show ();
main()
{
show ();
}
void show ()
{
………………
}
• Basically Functions in C and C++ have the same importance and the
applications.
• Also in C++ functions and the operators can be
Overloaded.
MAIN Function:
• No return type for main() in C.
• In C++ main() always returns an integer value to the operating system.
• That is why we always have a return() statement at the end of the main().
• Operating system checks the return value as the function has been
successfully executed or not.
Function Prototyping
• Function Prototype is a kind of template that is used by compiler to ensure
that proper arguments are passed and return value is treated correctly.
• Earlier C did not has the prototyping, It was firstly introduced in C++ then
it was adopted in ANSI C. However it is optional in C but compulsory in
C++.
returntype function name (argument list)
• The names of the arguments are optional in declaration but must in the
function definition.
Call by Reference
• When the values are passed to the functions they are using the copies of the original
variables. It will create a problem when we have to change the original variables.
• But in case of Call be Reference we pass the addresses of the variables hence all the
operations are performed on the original variables.
• Example: Swapping
void swap(int a, int b)
{ int t;
t=a;
a=b;
b=t;
}
swap(m,n);
void swap(int *a, int *b)
{ int
t=*a;
*a=*b;
*b=t;
}
Swap(&x, &y);
Return by Reference
int & max(int x, int y)
{
if (x>y)
return x;
else
return y;
}
This function will return the address of either x or y.
Inline Functions
• When a function is called substantial time is wasted the shifting of the
control. It adds more overheads when the size of the function is very small.
• One alternative to it is Macros, but their errors are not checked during the
compilation.
• In C++ we have inline functions. Here the compiler replaces the function
call with the corresponding function code.
inline function-header
{ function body }
inline float cube(float a)
{
return(a*a*a);
}
Calling:
c=cube(3.0);
d=cube(2.5+1.5);
Inline Functions contd..
• The Inline functions are advantageous only when the size of the function is
too small, if we use the same technique for the bigger functions the benefits
of the Inline functions will be lost.
• In case of Inline function the control doesn't go any where.
• The Inline Keyword is just a request to the compiler not the command, the
compiler may ignore the request if the size of the function is too large,
Then it will be treated as normal functions.
• The Inline will not work in the following cases;
1. Functions having the loop, switch or goto statement.
2. Functions not returning any values if a return statement exists.
3. If functions have static variables.
4. If functions are recursive.
Using the Inline functions every time the function is invoked new memory is
allocated so trade-off becomes necessary.
Default Arguments
• We can call a function in C++, without specifying all the arguments.
• We can give some default values in the function prototype.
float amount(float p, int t, float rate =0.15);
Now if we call value = amount(5000,7);
Then internally It will be converted into
value = amount(5000,7,0.15);
• Important here is that the default values must be added from right to left.
Const Arguments
• This tells the compiler that the function should not modify the argument.
int strlen (const char *p);
int length (const string &s);
Specially it is used when we pass arguments as reference of as pointers.
Inline functions
• An inline function is a function that is
expanded in line when it is invoked.
• That is, the compiler replaces the function call
with function definition.
Why do we use inline functions
• Every time a function is called it takes a lot of
extra time in executing series of instructions
for tasks such as jumping to function, saving
registers, returning to calling function.
• When function is small, huge execution time is
spent in such overheads
• To eliminate the cost of calling small
functions, INLINE functions are used.
SYNTAX
Inline function-header
{
Function body
}
Example
inline float square(float x)
{
return x*x;
}
void main()
{
float a,y;
a=square(y);
}
• During compilation this
code is treated as:
void main()
{
float a,y;
a=y*y;
}
• While making inline functions all we need to
do is to prefix the keyword inline to function
definition.
• All inline functions must be defined
before they are called.
• Usually, the functions are made inline
when they are small enough to be
defined in 1 or 2 lines.
Situations where inline expansion may
not work:
• For functions returning values, if a loop, a
switch or a goto exists.
• For functions not returning value, if a return
statement exists.
• If function contains static variables
• If inline functions are recursive.
Illustration
• #include<iostream.h>
• #include<conio.h>
• inline int mult(int x,int y)
• {
• return(x*y);
• }
• inline int sum(int a,int b)
• {
• return(a+b);
• }
• int main()
• {
• int p,q;
• cout<<mult(p,q);
• cout<<sum(p,q);
• return 0;
• }
Default arguments
• To call a function without specifying its
arguments.
• In such cases, function assigns a default value
to the parameter which does not have a
matching arguments in the function call.
• Default values are specified when function is
declared.
Example of function declaration with
default values
float amount(float principal,int time,int rate=2);
// default value of 2 is assigned to rate
Amount(5000,5);
// this function call passes value of 5000 to
principal and 5 to time and function uses
default value of 2 for rate.
Amount(5000,5,1); //no missing argument,it
passes an explicit value of 1 to rate
• NOTE: only trailing arguments can have
default values.
• We must add default values from right to left.
We can not provide default value to an
argument in the middle of argument list.
int sum(int i, int j=5, int k=9); //Right
int sum(int i=5, int j); //wrong
int sum(int i=0, int j; int k=5); //wrong
Advantages
• We can use default arguments to add new
parameters to existing functions.
• Default arguments can be used to combine
similar functions into one.
Function Overloading
• Overloading; Using the same thing for different purposes.
When a same function name performs a variety of tasks is also
called function polymorphism in OOP.
• The operation to be performed by the function will depend upon the type
and the no. of arguments passed to the function. It is done like this :
1. The compiler will try to find the exact match, actual type and no. of
arguments.
2. If not the compiler uses integral promotions
char to int
float to double
3 Then built in conversions are done, and if there is no match then compiler
will generate an error message.
Precautions:
1. Unrelated functions should not be overloaded.
2. Default arguments can be used sometimes at place of overloading.
Function Overloading
• #include<iostream.h>
int volume (int);
double volume (double, int);
long volume (long, int, int);
int main()
{
cout<<Volume(10)<<ā€œnā€;
cout<<Volume(2.5,8)<<ā€œnā€;
cout<<Volume(100L,75,15)<<ā€œnā€;
return 0;
}
Int volume(int s)
{ return(s*s*s);
}
Int volume(double r, int h)
{ return(3.14519*r*r*h);
}
Int volume(long I, int b, int h)
{ return(l*b*h);
}
Output
1000
157.26
112500
Ad

More Related Content

Similar to Function in C++, Methods in C++ coding programming (20)

85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
Mukund Trivedi
Ā 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
Ā 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
Ā 
Inline function
Inline functionInline function
Inline function
Tech_MX
Ā 
Function Overloading Call by value and call by reference
Function Overloading Call by value and call by referenceFunction Overloading Call by value and call by reference
Function Overloading Call by value and call by reference
TusharAneyrao1
Ā 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
Ā 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
Ā 
Functions
FunctionsFunctions
Functions
Golda Margret Sheeba J
Ā 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Bharath904863
Ā 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
vanshhans21102005
Ā 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
Mukund Trivedi
Ā 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
Praveen M Jigajinni
Ā 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ashim Lamichhane
Ā 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
Ā 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
Ā 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
Ā 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
bhawna kol
Ā 
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvdFunctions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
scs150831
Ā 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection
Ā 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
Ā 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
Mukund Trivedi
Ā 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
Ā 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
Ā 
Inline function
Inline functionInline function
Inline function
Tech_MX
Ā 
Function Overloading Call by value and call by reference
Function Overloading Call by value and call by referenceFunction Overloading Call by value and call by reference
Function Overloading Call by value and call by reference
TusharAneyrao1
Ā 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
Ā 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
Ā 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
vanshhans21102005
Ā 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
Mukund Trivedi
Ā 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
Ā 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
bhawna kol
Ā 
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvdFunctions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
scs150831
Ā 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
Ā 

Recently uploaded (20)

Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
Ā 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
Ā 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
Ā 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
Ā 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
Ā 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
Ā 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
Ā 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
Ā 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
Ā 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
Ā 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
Ā 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
Ā 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
Ā 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
Ā 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
Ā 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
Ā 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
Ā 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
Ā 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
Ā 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
Ā 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
Ā 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
Ā 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
Ā 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
Ā 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
Ā 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
Ā 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
Ā 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
Ā 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
Ā 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
Ā 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
Ā 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
Ā 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
Ā 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
Ā 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
Ā 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
Ā 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
Ā 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
Ā 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
Ā 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
Ā 
Ad

Function in C++, Methods in C++ coding programming

  • 2. Introduction • Functions are the main tool of Structured Programming. • Functions decrease the size of program by calling the function at different places in the program. See the Syntax in C: void show (); main() { show (); } void show () { ……………… }
  • 3. • Basically Functions in C and C++ have the same importance and the applications. • Also in C++ functions and the operators can be Overloaded. MAIN Function: • No return type for main() in C. • In C++ main() always returns an integer value to the operating system. • That is why we always have a return() statement at the end of the main(). • Operating system checks the return value as the function has been successfully executed or not.
  • 4. Function Prototyping • Function Prototype is a kind of template that is used by compiler to ensure that proper arguments are passed and return value is treated correctly. • Earlier C did not has the prototyping, It was firstly introduced in C++ then it was adopted in ANSI C. However it is optional in C but compulsory in C++. returntype function name (argument list) • The names of the arguments are optional in declaration but must in the function definition.
  • 5. Call by Reference • When the values are passed to the functions they are using the copies of the original variables. It will create a problem when we have to change the original variables. • But in case of Call be Reference we pass the addresses of the variables hence all the operations are performed on the original variables. • Example: Swapping void swap(int a, int b) { int t; t=a; a=b; b=t; } swap(m,n); void swap(int *a, int *b) { int t=*a; *a=*b; *b=t; } Swap(&x, &y);
  • 6. Return by Reference int & max(int x, int y) { if (x>y) return x; else return y; } This function will return the address of either x or y.
  • 7. Inline Functions • When a function is called substantial time is wasted the shifting of the control. It adds more overheads when the size of the function is very small. • One alternative to it is Macros, but their errors are not checked during the compilation. • In C++ we have inline functions. Here the compiler replaces the function call with the corresponding function code. inline function-header { function body } inline float cube(float a) { return(a*a*a); } Calling: c=cube(3.0); d=cube(2.5+1.5);
  • 8. Inline Functions contd.. • The Inline functions are advantageous only when the size of the function is too small, if we use the same technique for the bigger functions the benefits of the Inline functions will be lost. • In case of Inline function the control doesn't go any where. • The Inline Keyword is just a request to the compiler not the command, the compiler may ignore the request if the size of the function is too large, Then it will be treated as normal functions. • The Inline will not work in the following cases; 1. Functions having the loop, switch or goto statement. 2. Functions not returning any values if a return statement exists. 3. If functions have static variables. 4. If functions are recursive. Using the Inline functions every time the function is invoked new memory is allocated so trade-off becomes necessary.
  • 9. Default Arguments • We can call a function in C++, without specifying all the arguments. • We can give some default values in the function prototype. float amount(float p, int t, float rate =0.15); Now if we call value = amount(5000,7); Then internally It will be converted into value = amount(5000,7,0.15); • Important here is that the default values must be added from right to left.
  • 10. Const Arguments • This tells the compiler that the function should not modify the argument. int strlen (const char *p); int length (const string &s); Specially it is used when we pass arguments as reference of as pointers.
  • 11. Inline functions • An inline function is a function that is expanded in line when it is invoked. • That is, the compiler replaces the function call with function definition.
  • 12. Why do we use inline functions • Every time a function is called it takes a lot of extra time in executing series of instructions for tasks such as jumping to function, saving registers, returning to calling function. • When function is small, huge execution time is spent in such overheads • To eliminate the cost of calling small functions, INLINE functions are used.
  • 14. Example inline float square(float x) { return x*x; } void main() { float a,y; a=square(y); } • During compilation this code is treated as: void main() { float a,y; a=y*y; }
  • 15. • While making inline functions all we need to do is to prefix the keyword inline to function definition. • All inline functions must be defined before they are called. • Usually, the functions are made inline when they are small enough to be defined in 1 or 2 lines.
  • 16. Situations where inline expansion may not work: • For functions returning values, if a loop, a switch or a goto exists. • For functions not returning value, if a return statement exists. • If function contains static variables • If inline functions are recursive.
  • 17. Illustration • #include<iostream.h> • #include<conio.h> • inline int mult(int x,int y) • { • return(x*y); • } • inline int sum(int a,int b) • { • return(a+b); • } • int main() • { • int p,q; • cout<<mult(p,q); • cout<<sum(p,q); • return 0; • }
  • 18. Default arguments • To call a function without specifying its arguments. • In such cases, function assigns a default value to the parameter which does not have a matching arguments in the function call. • Default values are specified when function is declared.
  • 19. Example of function declaration with default values float amount(float principal,int time,int rate=2); // default value of 2 is assigned to rate Amount(5000,5); // this function call passes value of 5000 to principal and 5 to time and function uses default value of 2 for rate. Amount(5000,5,1); //no missing argument,it passes an explicit value of 1 to rate
  • 20. • NOTE: only trailing arguments can have default values. • We must add default values from right to left. We can not provide default value to an argument in the middle of argument list. int sum(int i, int j=5, int k=9); //Right int sum(int i=5, int j); //wrong int sum(int i=0, int j; int k=5); //wrong
  • 21. Advantages • We can use default arguments to add new parameters to existing functions. • Default arguments can be used to combine similar functions into one.
  • 22. Function Overloading • Overloading; Using the same thing for different purposes. When a same function name performs a variety of tasks is also called function polymorphism in OOP. • The operation to be performed by the function will depend upon the type and the no. of arguments passed to the function. It is done like this : 1. The compiler will try to find the exact match, actual type and no. of arguments. 2. If not the compiler uses integral promotions char to int float to double 3 Then built in conversions are done, and if there is no match then compiler will generate an error message. Precautions: 1. Unrelated functions should not be overloaded. 2. Default arguments can be used sometimes at place of overloading.
  • 23. Function Overloading • #include<iostream.h> int volume (int); double volume (double, int); long volume (long, int, int); int main() { cout<<Volume(10)<<ā€œnā€; cout<<Volume(2.5,8)<<ā€œnā€; cout<<Volume(100L,75,15)<<ā€œnā€; return 0; } Int volume(int s) { return(s*s*s); } Int volume(double r, int h) { return(3.14519*r*r*h); } Int volume(long I, int b, int h) { return(l*b*h); } Output 1000 157.26 112500