SlideShare a Scribd company logo
Functions
Furqan Aziz
Function
 A function groups a number of program statements into
a unit and gives it a name.
 This unit can then be invoked from other parts of the
program.
 Advantages of using functions
 Conceptual organization of a program.
 Reduced program size.
 Code reusability.
 Easy to maintain and debug.
Simple Functions
#include <iostream>
using namespace std;
void starLine();
int main(){
starLine();
cout<<"NtN*10tN*100tN*1000n";
starLine();
for(int i=0; i<5; i++){
cout<<i<<"t"<<i*10<<"t";
cout<<i*100<<"t"<<i*1000<<endl;
}
starLine();
}
void starLine(){
for(int i=0; i<30; i++)
cout<<"*";
cout<<endl;
return;
}
Sample output
How many functions are there in this program.
The Function Declaration
 Just as you can’t use a variable without first telling the compiler what
it is, you also can’t use a function without telling the compiler about it.
 There are two ways to do this.
 Declare the function before it is called, and defined it somewhere else.
 Declared and define it before it’s called.
 Syntax:
 void starline();
 The declaration tells the compiler that at some later point we plan to
present a function called starline.
 Function declarations are also called prototypes , since they provide
a model or blueprint for the function.
The Function Declaration
 A function can return a value of any basic type (like int,
float, char etc) or any user defined type (Class or
Structure).
 The keyword void specifies that the function has no
return value
 A function can accept any number/type of arguments
(also called parameters list).
 The empty parentheses indicate that it takes no
arguments.
Calling the Function
 The following statement will call the function starline().
 starline();
 This is all we need to call the function: the function name,
followed by parentheses.
 The syntax of the call is very similar to that of the
declaration, except that the return type is not used.
 The call is terminated by a semicolon.
 Executing the call statement causes the function to execute;
i.e.,
 control is transferred to the function,
 the statements in the function definition are executed,
 The control returns to the statement following the function call.
The Function Definition
 The function definition contains the actual code for the
function.
 The definition consists of a line called the declarator,
followed by the function body .
 The function body is composed of the statements that make
up the function, delimited by braces.
 The declarator must agree with the declaration: It must use
the same function name, have the same argument types in
the same order (if there are arguments), and have the same
return type.
 Notice that the declarator is not terminated by a semicolon.
Function Components
Comparison with Library
Functions
 Library functions are inbuilt functions which are grouped together
and placed in common place called library.
 Each library function performs a specific task.
 We have already used some of the library functions, such as
 ch = getch();
 Where are the declaration and definition of this library function?
 The declaration is in the header file specified at the beginning of
the program.
 The definition (compiled into executable code) is in a library file
that’s linked automatically to your program when you build it.
 Note that the getch() function returns a character and its does not
accept any arguments.
Eliminating the Declaration
 The second approach to inserting a function into a
program is to eliminate the function declaration and
place the function definition (the function itself) in the
listing before the first call to the function.
Eliminating the Declaration
#include <iostream>
using namespace std;
void starLine(){
for(int i=0; i<30; i++)
cout<<"*";
cout<<endl;
return;
}
int main(){
starLine();
cout<<"NtN*10tN*100tN*1000n";
starLine();
for(int i=0; i<5; i++){
cout<<i<<"t"<<i*10<<"t";
cout<<i*100<<"t"<<i*1000<<endl;
}
starLine();
}
Passing Arguments to
Functions
 An argument is a piece of data (an int value, for
example) passed from a program to the function.
 Arguments allow a function to operate with different
values, or even to do different things, depending on the
requirements of the program calling it.
Passing constants
#include <iostream>
using namespace std;
void starLine(char ch, int n);
int main(){
starLine('-',50);
cout<<'t';
starLine('=',30);
cout<<"tNtN*10tN*100tN*1000n";
cout<<"t";
starLine('=',30);
for(int i=0; i<5; i++){
cout<<"t"<<i<<"t"<<i*10<<"t";
cout<<i*100<<"t"<<i*1000<<endl;
}
cout<<'t';
starLine('=',30);
starLine('-',50);
cout<<endl;
}
void starLine(char ch, int n){
for(int i=0; i<n; i++)
cout<<ch;
cout<<endl;
return;
}
Sample output
 The function declaration looks like
 void starLine(char ch, int n);
 The items in the parentheses are the data types of the arguments
that will be sent to the function.
 These are called parameters.
 In a function call, specific values—constants in this case—are
inserted in the appropriate place in the parentheses. These are
called arguments:
 starLine(‘=‘, 30);
 The values supplied in the call must be of the types specified in
the declaration: the first argument must be of type char and the
second argument must be of type int.
 The types in the declaration and the definition must also agree.
Passing Variables
#include <iostream>
using namespace std;
void repchar(char, int);
int main()
{
char chin;
int nin;
cout << "Enter a character: ";
cin >> chin;
cout << "Enter number of times to repeat it: ";
cin >> nin;
repchar(chin, nin);
return 0;
}
void repchar(char ch, int n) //function declarator
{
for(int j=0; j<n; j++) //function body
cout << ch;
cout << endl;
}
Sample output
Passing arguments to a
function
 There are two ways to pass arguments to a function.
 Passing by value
 Passing by reference
Passing by Value
 In passing by value, function creates a new variable for
each of the parameter.
 The parameters are initialized with the values of the
arguments.
 When the function finishes its execution, these
variables are deleted from the memory.
 If you change the value of a parameter, the original
value remains unchanged.
Returning Values from
Functions
 When a function completes its execution, it can return a
single value to the calling program.
 Usually this return value consists of an answer to the
problem the function has solved.
 When a function returns a value, the data type of this
value must be specified.
 When a function returns a value, the value from the
variable in the called function is copied to the one
assigned to the function call into the variable in the
calling function.
Example
#include <iostream>
using namespace std;
float lbstokg(float); //declaration
int main()
{
float lbs, kgs;
cout << "nEnter your weight in pounds: ";
cin >> lbs;
kgs = lbstokg(lbs);
cout << "Your weight in kilograms is " << kgs << endl;
return 0;
}
float lbstokg(float pounds)
{
float kilograms = 0.453592 * pounds;
return kilograms;
}
Sample output
Eliminating Unnecessary
Variables
#include <iostream>
using namespace std;
float lbstokg(float); //declaration
int main()
{
float lbs;
cout << “nEnter your weight in pounds: “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbstokg(lbs);
cout << endl;
return 0;
}
float lbstokg(float pounds)
{
return 0.453592 * pounds;
}
Pass by reference
 A reference provides an alias — i.e., a different name — for
a variable.
 One of the most important uses for references is in passing
arguments to functions.
 Passing arguments by reference uses a different
mechanism. Instead of a value being passed to the function,
a reference to the original variable, in the calling program, is
passed.
 An important advantage of passing by reference is that the
function can access the actual variables in the calling
program
Example
#include <iostream>
using namespace std;
int main()
{
void intfrac(float, float&, float&); //declaration
float number, intpart, fracpart; //float variables
do {
cout << “nEnter a real number: “; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << “Integer part is “ << intpart //print them
<< “, fraction part is “ << fracpart << endl;
} while( number != 0.0 ); //exit loop on 0.0
return 0;
}
//--------------------------------------------------------------
void intfrac(float n, float& intp, float& fracp)
{
long temp = static_cast<long>(n); //convert to long,
intp = static_cast<float>(temp); //back to float
fracp = n - intp; //subtract integer part
}
Sample output
Swapping of variables
#include <iostream>
using namespace std;
void swap_nums(int&, int&);
int main()
{
int n1=99, n2=11;
int n3=22, n4=77;
swap_nums(n1, n2);
swap_nums(n3, n4);
cout << "n1=" << n1 << endl; //print out all numbers
cout << "n2=" << n2 << endl;
cout << "n3=" << n3 << endl;
cout << "n4=" << n4 << endl;
return 0;
}
void swap_nums(int& numb1, int& numb2)
{
int temp = numb1; //swap them
numb1 = numb2;
numb2 = temp;
}
Sample output
Function Overloading
 An overloaded function appears to perform different
activities depending on the kind of data sent to it.
 Overloading is like the joke about the famous
scientist who insisted that the thermos bottle was
the greatest invention of all time. Why? “It’s a
miracle device,” he said. “It keeps hot things hot,
but cold things it keeps cold. How does it know?”
Overloaded Functions
 Two functions with same name but different
number/type of arguments are called overloaded
functions.
 Example (different type of arguments)
 int sum (int x, int y);
 float sum (float x, float y);
 Example (different number of arguments)
 double inchToMeter (int feet, double inches);
 double inchToMeter (double feet);
Example
#include <iostream>
using namespace std;
void repchar(); //declarations
void repchar(char);
void repchar(char, int);
int main()
{
repchar();
repchar(‘=’);
repchar(‘+’, 30);
return 0;
}
void repchar()
{
for(int j=0; j<45; j++)
cout << ‘*’; // always prints asterisk
cout << endl;
}
void repchar(char ch)
{
for(int j=0; j<45; j++)
cout << ch;
cout << endl;
}
void repchar(char ch, int n)
{
for(int j=0; j<n; j++)
cout << ch;
cout << endl;
}
This program prints out three lines of characters. Here’s the output:
*********************************************
=============================================
++++++++++++++++++++++++++++++
Recursion
 A function can call itself, and this is called recursion.
 when used correctly this technique can be surprisingly
powerful.
Example: Factorial
#include <iostream>
using namespace std;
unsigned long factfunc(unsigned long); //declaration
int main()
{
int n; //number entered by user
unsigned long fact; //factorial
cout << "Enter an integer: ";
cin >> n;
fact = factfunc(n);
cout << "Factorial of " << n << " is " << fact << endl;
return 0;
}
unsigned long factfunc(unsigned long n)
{
if(n > 1)
return n * factfunc(n-1); //self call
else
return 1;
}
Inline Functions
 Functions save memory space because all the calls to the function
cause the same code to be executed; the function body need not
be duplicated in memory.
 When the compiler sees a function call, it normally generates a
jump to the function.
 At the end of the function it jumps back to the instruction following
the call.
 While this sequence of events may save memory space, it takes
some extra time.
 To save execution time in short functions, you may elect to put the
code in the function body directly inline with the code in the calling
program.
Inline Functions
 To declare a function inline, you need to specify the
keyword inline.
 You should be aware that the inline keyword is actually
just a request to the compiler.
 Sometimes the compiler will ignore the request and
compile the function as a normal function. It might
decide the function is too long to be inline, for instance.
Example
#include <iostream>
using namespace std;
inline float lbstokg(float pounds)
{
return 0.453592 * pounds;
}
//--------------------------------------------------------------
int main()
{
float lbs;
cout << "nEnter your weight in pounds: ";
cin >> lbs;
cout << "Your weight in kilograms is " << lbstokg(lbs)
<< endl;
return 0;
}
Default Arguments
 A function can be called without specifying all its
arguments.
 For this to work, the function declaration must provide
default values for those arguments that are not
specified.
 These are called default arguments.
Example
#include <iostream>
using namespace std;
void repchar(char='*', int=45); //declaration with
//default arguments
int main()
{
repchar(); //prints 45 asterisks
repchar('='); //prints 45 equal signs
repchar('+', 30); //prints 30 plus signs
return 0;
}
//--------------------------------------------------------------
void repchar(char ch, int n) //defaults supplied
{ // if necessary
for(int j=0; j<n; j++) //loops n times
cout << ch; //prints ch
cout << endl;
}
Default Arguments
 Remember that missing arguments must be the trailing
arguments—those at the end of thr argument list.
 You can leave out the last three arguments, but you
can’t leave out the next-to-last and then put in the last.
Scope and Storage Class
 The scope of a variable determines which parts of the
program can access it, and its storage class determines how
long it stays in existence.
 Two different kinds of scope are important here: local and
file.
 Variables with local scope are visible only within a block.
 Variables with file scope are visible throughout a file.
 There are two storage classes: automatic and static.
 Variables with storage class automatic exist during the lifetime
of the function in which they’re defined.
 Variables with storage class static exist for the lifetime of the
program.
 A block is basically the code between an opening brace and
a closing brace. Thus a function body is a block.
Local variables
 Variables defined within a function body are called local
variables. A variable scope is also called visibility.
 They have local scope, i.e., they can only be accessed
inside the block where they are defined.
 However, they are also sometimes called automatic
variables, because they have the automatic storage class.
 The time period between the creation and destruction of a
variable is called its lifetime.
 The lifetime of a local variable coincides with the time when
the function in which it is defined is executing.
Example
void somefunc()
{
int somevar; //local variables
float othervar;
somevar = 10; //OK
othervar = 11; //OK
nextvar = 12; //illegal: not visible in somefunc()
}
void otherfunc()
{
int nextvar; //local variable
somevar = 20; //illegal: not visible in otherfunc()
othervar = 21; //illegal: not visible in otherfunc()
nextvar = 22; //OK
}
Global Variables
 A global variable is visible to all the functions in a file.
 More precisely, it is visible to all those functions that follow
the variable’s definition in the listing.
 While local variables are defined within functions, global
variables are defined outside of any function.
 Usually you want global variables to be visible to all
functions, so you put their declarations at the beginning of
the listing.
 Global variables are also sometimes called external
variables, since they are defined external to any function.
Exmaple
#include <iostream>
using namespace std;
#include <conio.h> //for getch()
char ch = ‘a’; //global variable ch
void getachar(); //function declarations
void putachar();
int main()
{
while( ch != ‘r’ ) //main() accesses ch {
getachar();
putachar();
}
cout << endl;
return 0;
}
//--------------------------------------------------------------
void getachar() //getachar() accesses ch {
ch = getch();
}
//--------------------------------------------------------------
void putachar() //putachar() accesses ch {
cout << ch;
}
Global Variables: Initialization
 If a global variable is initialized, it takes place when the
program is first loaded.
 If a global variable is not initialized explicitly by the
program, then it is initialized automatically to 0 when it
is created.
 This is unlike local variables, which are not initialized
and probably contain random or garbage values when
they are created
Lifetime and Visibility
 Global variables have storage class static, which
means they exist for the life of the program
 Memory space is set aside for them when the program
begins, and continues to exist until the program ends.
 You don’t need to use the keyword static when
declaring global variables; they are given this storage
class automatically.
 Global variables are visible in the file in which they are
defined, starting at the point where they are defined.
Static Local Variables
 A static local variable has the visibility of an automatic local
variable (that is, inside the function containing it).
 However, its lifetime is the same as that of a global variable,
except that it doesn’t come into existence until the first call to
the function containing it.
 Thereafter it remains in existence for the life of the program.
 Static local variables are used when it’s necessary for a
function to remember a value when it is not being executed;
that is, between calls to the function.
Example
#include <iostream>
using namespace std;
float getavg(float); //declaration
int main()
{
float data=1, avg;
while( data != 0 )
{
cout << “Enter a number: “;
cin >> data;
avg = getavg(data);
cout << “New average is “ << avg << endl;
}
return 0;
}
//--------------------------------------------------------------
float getavg(float newdata)
{
static float total = 0; //static variables are initialized
static int count = 0; // only once per program
count++; //increment count
total += newdata; //add new data to total
return total / count; //return the new average
}
Static variables
 Initialization: When static variables are initialized, as
total and count are in getavg() , the initialization takes
place only once—the first time their function is called.
They are not reinitialized on subsequent calls to the
function, as ordinary local variables are.
 Storage: local variables and function arguments are
stored on the stack, while global and static variables
are stored on the heap.
Storage types

More Related Content

What's hot

Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Control statements
Control statementsControl statements
Control statements
Kanwalpreet Kaur
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
C functions
C functionsC functions
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Fatima Kate Tanay
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
Abdul Rehman
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 

What's hot (20)

Functions in c
Functions in cFunctions in c
Functions in c
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Control statements
Control statementsControl statements
Control statements
 
Function in C
Function in CFunction in C
Function in C
 
structure and union
structure and unionstructure and union
structure and union
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Call by value
Call by valueCall by value
Call by value
 
C functions
C functionsC functions
C functions
 
Nested loops
Nested loopsNested loops
Nested loops
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
functions of C++
functions of C++functions of C++
functions of C++
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 

Viewers also liked

C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Functions
FunctionsFunctions
Functions
Online
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
Function overloading
Function overloadingFunction overloading
Function overloading
Jnyanaranjan Dash
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
NUST Stuff
 
Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
sanya6900
 
Family Law Magazine
Family Law MagazineFamily Law Magazine
Family Law Magazine
Thomas Mastromatto NMLS #145824
 
Trabajotesismelinda
TrabajotesismelindaTrabajotesismelinda
Trabajotesismelinda
Brayan MiGuel
 
Comunicación estratégica de Aqualand
Comunicación estratégica de AqualandComunicación estratégica de Aqualand
Comunicación estratégica de Aqualand
kristinaah
 
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Communardo GmbH
 
Mba college in bangalore - NIBE
Mba college in bangalore - NIBEMba college in bangalore - NIBE
Mba college in bangalore - NIBE
NIBE ( National Institute Of Busiess Excellence )
 
Formations PAO & 3D
Formations PAO & 3DFormations PAO & 3D
Formations PAO & 3D
KIELA Consulting
 
Visual cryptography1
Visual cryptography1Visual cryptography1
Visual cryptography1patisa
 
ProCor audience survey results
ProCor audience survey resultsProCor audience survey results
ProCor audience survey results
procor
 
Personal disciplina
Personal disciplinaPersonal disciplina
Personal disciplinaconvertidor
 
Online Werbung
Online WerbungOnline Werbung
Online Werbung
Wolfgang Stock
 

Viewers also liked (20)

C++ Function
C++ FunctionC++ Function
C++ Function
 
Functions
FunctionsFunctions
Functions
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Family Law Magazine
Family Law MagazineFamily Law Magazine
Family Law Magazine
 
Trabajotesismelinda
TrabajotesismelindaTrabajotesismelinda
Trabajotesismelinda
 
Comunicación estratégica de Aqualand
Comunicación estratégica de AqualandComunicación estratégica de Aqualand
Comunicación estratégica de Aqualand
 
24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman24 10-12 presentation vca marco tiggelman
24 10-12 presentation vca marco tiggelman
 
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
Microsharing Im Unternehmen: Wie Dokumentieren und Lernen Teil der täglichen ...
 
Mba college in bangalore - NIBE
Mba college in bangalore - NIBEMba college in bangalore - NIBE
Mba college in bangalore - NIBE
 
Formations PAO & 3D
Formations PAO & 3DFormations PAO & 3D
Formations PAO & 3D
 
Visual cryptography1
Visual cryptography1Visual cryptography1
Visual cryptography1
 
ProCor audience survey results
ProCor audience survey resultsProCor audience survey results
ProCor audience survey results
 
Fb para empresas mod3 - ud2y3
Fb para empresas   mod3 - ud2y3Fb para empresas   mod3 - ud2y3
Fb para empresas mod3 - ud2y3
 
Personal disciplina
Personal disciplinaPersonal disciplina
Personal disciplina
 
Online Werbung
Online WerbungOnline Werbung
Online Werbung
 

Similar to Function C++

Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
Function in c
Function in cFunction in c
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
Jari Abbas
 
Function
Function Function
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
SURBHI SAROHA
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functionsAlisha Korpal
 
Functions in c
Functions in cFunctions in c
Functions in c
SunithaVesalpu
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
C function
C functionC function
C function
thirumalaikumar3
 

Similar to Function C++ (20)

Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Function in c
Function in cFunction in c
Function in c
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Function in c
Function in cFunction in c
Function in c
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Functions
FunctionsFunctions
Functions
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
functions
functionsfunctions
functions
 
Function
Function Function
Function
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
C function
C functionC function
C function
 

Recently uploaded

The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 

Recently uploaded (20)

The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 

Function C++

  • 2. Function  A function groups a number of program statements into a unit and gives it a name.  This unit can then be invoked from other parts of the program.  Advantages of using functions  Conceptual organization of a program.  Reduced program size.  Code reusability.  Easy to maintain and debug.
  • 3.
  • 4. Simple Functions #include <iostream> using namespace std; void starLine(); int main(){ starLine(); cout<<"NtN*10tN*100tN*1000n"; starLine(); for(int i=0; i<5; i++){ cout<<i<<"t"<<i*10<<"t"; cout<<i*100<<"t"<<i*1000<<endl; } starLine(); } void starLine(){ for(int i=0; i<30; i++) cout<<"*"; cout<<endl; return; }
  • 5. Sample output How many functions are there in this program.
  • 6. The Function Declaration  Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function without telling the compiler about it.  There are two ways to do this.  Declare the function before it is called, and defined it somewhere else.  Declared and define it before it’s called.  Syntax:  void starline();  The declaration tells the compiler that at some later point we plan to present a function called starline.  Function declarations are also called prototypes , since they provide a model or blueprint for the function.
  • 7. The Function Declaration  A function can return a value of any basic type (like int, float, char etc) or any user defined type (Class or Structure).  The keyword void specifies that the function has no return value  A function can accept any number/type of arguments (also called parameters list).  The empty parentheses indicate that it takes no arguments.
  • 8. Calling the Function  The following statement will call the function starline().  starline();  This is all we need to call the function: the function name, followed by parentheses.  The syntax of the call is very similar to that of the declaration, except that the return type is not used.  The call is terminated by a semicolon.  Executing the call statement causes the function to execute; i.e.,  control is transferred to the function,  the statements in the function definition are executed,  The control returns to the statement following the function call.
  • 9. The Function Definition  The function definition contains the actual code for the function.  The definition consists of a line called the declarator, followed by the function body .  The function body is composed of the statements that make up the function, delimited by braces.  The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order (if there are arguments), and have the same return type.  Notice that the declarator is not terminated by a semicolon.
  • 10.
  • 12. Comparison with Library Functions  Library functions are inbuilt functions which are grouped together and placed in common place called library.  Each library function performs a specific task.  We have already used some of the library functions, such as  ch = getch();  Where are the declaration and definition of this library function?  The declaration is in the header file specified at the beginning of the program.  The definition (compiled into executable code) is in a library file that’s linked automatically to your program when you build it.  Note that the getch() function returns a character and its does not accept any arguments.
  • 13. Eliminating the Declaration  The second approach to inserting a function into a program is to eliminate the function declaration and place the function definition (the function itself) in the listing before the first call to the function.
  • 14. Eliminating the Declaration #include <iostream> using namespace std; void starLine(){ for(int i=0; i<30; i++) cout<<"*"; cout<<endl; return; } int main(){ starLine(); cout<<"NtN*10tN*100tN*1000n"; starLine(); for(int i=0; i<5; i++){ cout<<i<<"t"<<i*10<<"t"; cout<<i*100<<"t"<<i*1000<<endl; } starLine(); }
  • 15. Passing Arguments to Functions  An argument is a piece of data (an int value, for example) passed from a program to the function.  Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.
  • 16. Passing constants #include <iostream> using namespace std; void starLine(char ch, int n); int main(){ starLine('-',50); cout<<'t'; starLine('=',30); cout<<"tNtN*10tN*100tN*1000n"; cout<<"t"; starLine('=',30); for(int i=0; i<5; i++){ cout<<"t"<<i<<"t"<<i*10<<"t"; cout<<i*100<<"t"<<i*1000<<endl; } cout<<'t'; starLine('=',30); starLine('-',50); cout<<endl; } void starLine(char ch, int n){ for(int i=0; i<n; i++) cout<<ch; cout<<endl; return; }
  • 18.  The function declaration looks like  void starLine(char ch, int n);  The items in the parentheses are the data types of the arguments that will be sent to the function.  These are called parameters.  In a function call, specific values—constants in this case—are inserted in the appropriate place in the parentheses. These are called arguments:  starLine(‘=‘, 30);  The values supplied in the call must be of the types specified in the declaration: the first argument must be of type char and the second argument must be of type int.  The types in the declaration and the definition must also agree.
  • 19. Passing Variables #include <iostream> using namespace std; void repchar(char, int); int main() { char chin; int nin; cout << "Enter a character: "; cin >> chin; cout << "Enter number of times to repeat it: "; cin >> nin; repchar(chin, nin); return 0; } void repchar(char ch, int n) //function declarator { for(int j=0; j<n; j++) //function body cout << ch; cout << endl; }
  • 21. Passing arguments to a function  There are two ways to pass arguments to a function.  Passing by value  Passing by reference
  • 22. Passing by Value  In passing by value, function creates a new variable for each of the parameter.  The parameters are initialized with the values of the arguments.  When the function finishes its execution, these variables are deleted from the memory.  If you change the value of a parameter, the original value remains unchanged.
  • 23.
  • 24. Returning Values from Functions  When a function completes its execution, it can return a single value to the calling program.  Usually this return value consists of an answer to the problem the function has solved.  When a function returns a value, the data type of this value must be specified.  When a function returns a value, the value from the variable in the called function is copied to the one assigned to the function call into the variable in the calling function.
  • 25. Example #include <iostream> using namespace std; float lbstokg(float); //declaration int main() { float lbs, kgs; cout << "nEnter your weight in pounds: "; cin >> lbs; kgs = lbstokg(lbs); cout << "Your weight in kilograms is " << kgs << endl; return 0; } float lbstokg(float pounds) { float kilograms = 0.453592 * pounds; return kilograms; }
  • 27.
  • 28. Eliminating Unnecessary Variables #include <iostream> using namespace std; float lbstokg(float); //declaration int main() { float lbs; cout << “nEnter your weight in pounds: “; cin >> lbs; cout << “Your weight in kilograms is “ << lbstokg(lbs); cout << endl; return 0; } float lbstokg(float pounds) { return 0.453592 * pounds; }
  • 29. Pass by reference  A reference provides an alias — i.e., a different name — for a variable.  One of the most important uses for references is in passing arguments to functions.  Passing arguments by reference uses a different mechanism. Instead of a value being passed to the function, a reference to the original variable, in the calling program, is passed.  An important advantage of passing by reference is that the function can access the actual variables in the calling program
  • 30. Example #include <iostream> using namespace std; int main() { void intfrac(float, float&, float&); //declaration float number, intpart, fracpart; //float variables do { cout << “nEnter a real number: “; //number from user cin >> number; intfrac(number, intpart, fracpart); //find int and frac cout << “Integer part is “ << intpart //print them << “, fraction part is “ << fracpart << endl; } while( number != 0.0 ); //exit loop on 0.0 return 0; } //-------------------------------------------------------------- void intfrac(float n, float& intp, float& fracp) { long temp = static_cast<long>(n); //convert to long, intp = static_cast<float>(temp); //back to float fracp = n - intp; //subtract integer part }
  • 32.
  • 33. Swapping of variables #include <iostream> using namespace std; void swap_nums(int&, int&); int main() { int n1=99, n2=11; int n3=22, n4=77; swap_nums(n1, n2); swap_nums(n3, n4); cout << "n1=" << n1 << endl; //print out all numbers cout << "n2=" << n2 << endl; cout << "n3=" << n3 << endl; cout << "n4=" << n4 << endl; return 0; } void swap_nums(int& numb1, int& numb2) { int temp = numb1; //swap them numb1 = numb2; numb2 = temp; }
  • 35. Function Overloading  An overloaded function appears to perform different activities depending on the kind of data sent to it.  Overloading is like the joke about the famous scientist who insisted that the thermos bottle was the greatest invention of all time. Why? “It’s a miracle device,” he said. “It keeps hot things hot, but cold things it keeps cold. How does it know?”
  • 36. Overloaded Functions  Two functions with same name but different number/type of arguments are called overloaded functions.  Example (different type of arguments)  int sum (int x, int y);  float sum (float x, float y);  Example (different number of arguments)  double inchToMeter (int feet, double inches);  double inchToMeter (double feet);
  • 37. Example #include <iostream> using namespace std; void repchar(); //declarations void repchar(char); void repchar(char, int); int main() { repchar(); repchar(‘=’); repchar(‘+’, 30); return 0; } void repchar() { for(int j=0; j<45; j++) cout << ‘*’; // always prints asterisk cout << endl; } void repchar(char ch) { for(int j=0; j<45; j++) cout << ch; cout << endl; } void repchar(char ch, int n) { for(int j=0; j<n; j++) cout << ch; cout << endl; } This program prints out three lines of characters. Here’s the output: ********************************************* ============================================= ++++++++++++++++++++++++++++++
  • 38.
  • 39. Recursion  A function can call itself, and this is called recursion.  when used correctly this technique can be surprisingly powerful.
  • 40. Example: Factorial #include <iostream> using namespace std; unsigned long factfunc(unsigned long); //declaration int main() { int n; //number entered by user unsigned long fact; //factorial cout << "Enter an integer: "; cin >> n; fact = factfunc(n); cout << "Factorial of " << n << " is " << fact << endl; return 0; } unsigned long factfunc(unsigned long n) { if(n > 1) return n * factfunc(n-1); //self call else return 1; }
  • 41. Inline Functions  Functions save memory space because all the calls to the function cause the same code to be executed; the function body need not be duplicated in memory.  When the compiler sees a function call, it normally generates a jump to the function.  At the end of the function it jumps back to the instruction following the call.  While this sequence of events may save memory space, it takes some extra time.  To save execution time in short functions, you may elect to put the code in the function body directly inline with the code in the calling program.
  • 42.
  • 43. Inline Functions  To declare a function inline, you need to specify the keyword inline.  You should be aware that the inline keyword is actually just a request to the compiler.  Sometimes the compiler will ignore the request and compile the function as a normal function. It might decide the function is too long to be inline, for instance.
  • 44. Example #include <iostream> using namespace std; inline float lbstokg(float pounds) { return 0.453592 * pounds; } //-------------------------------------------------------------- int main() { float lbs; cout << "nEnter your weight in pounds: "; cin >> lbs; cout << "Your weight in kilograms is " << lbstokg(lbs) << endl; return 0; }
  • 45. Default Arguments  A function can be called without specifying all its arguments.  For this to work, the function declaration must provide default values for those arguments that are not specified.  These are called default arguments.
  • 46. Example #include <iostream> using namespace std; void repchar(char='*', int=45); //declaration with //default arguments int main() { repchar(); //prints 45 asterisks repchar('='); //prints 45 equal signs repchar('+', 30); //prints 30 plus signs return 0; } //-------------------------------------------------------------- void repchar(char ch, int n) //defaults supplied { // if necessary for(int j=0; j<n; j++) //loops n times cout << ch; //prints ch cout << endl; }
  • 47. Default Arguments  Remember that missing arguments must be the trailing arguments—those at the end of thr argument list.  You can leave out the last three arguments, but you can’t leave out the next-to-last and then put in the last.
  • 48. Scope and Storage Class  The scope of a variable determines which parts of the program can access it, and its storage class determines how long it stays in existence.  Two different kinds of scope are important here: local and file.  Variables with local scope are visible only within a block.  Variables with file scope are visible throughout a file.  There are two storage classes: automatic and static.  Variables with storage class automatic exist during the lifetime of the function in which they’re defined.  Variables with storage class static exist for the lifetime of the program.  A block is basically the code between an opening brace and a closing brace. Thus a function body is a block.
  • 49. Local variables  Variables defined within a function body are called local variables. A variable scope is also called visibility.  They have local scope, i.e., they can only be accessed inside the block where they are defined.  However, they are also sometimes called automatic variables, because they have the automatic storage class.  The time period between the creation and destruction of a variable is called its lifetime.  The lifetime of a local variable coincides with the time when the function in which it is defined is executing.
  • 50. Example void somefunc() { int somevar; //local variables float othervar; somevar = 10; //OK othervar = 11; //OK nextvar = 12; //illegal: not visible in somefunc() } void otherfunc() { int nextvar; //local variable somevar = 20; //illegal: not visible in otherfunc() othervar = 21; //illegal: not visible in otherfunc() nextvar = 22; //OK }
  • 51. Global Variables  A global variable is visible to all the functions in a file.  More precisely, it is visible to all those functions that follow the variable’s definition in the listing.  While local variables are defined within functions, global variables are defined outside of any function.  Usually you want global variables to be visible to all functions, so you put their declarations at the beginning of the listing.  Global variables are also sometimes called external variables, since they are defined external to any function.
  • 52. Exmaple #include <iostream> using namespace std; #include <conio.h> //for getch() char ch = ‘a’; //global variable ch void getachar(); //function declarations void putachar(); int main() { while( ch != ‘r’ ) //main() accesses ch { getachar(); putachar(); } cout << endl; return 0; } //-------------------------------------------------------------- void getachar() //getachar() accesses ch { ch = getch(); } //-------------------------------------------------------------- void putachar() //putachar() accesses ch { cout << ch; }
  • 53. Global Variables: Initialization  If a global variable is initialized, it takes place when the program is first loaded.  If a global variable is not initialized explicitly by the program, then it is initialized automatically to 0 when it is created.  This is unlike local variables, which are not initialized and probably contain random or garbage values when they are created
  • 54. Lifetime and Visibility  Global variables have storage class static, which means they exist for the life of the program  Memory space is set aside for them when the program begins, and continues to exist until the program ends.  You don’t need to use the keyword static when declaring global variables; they are given this storage class automatically.  Global variables are visible in the file in which they are defined, starting at the point where they are defined.
  • 55. Static Local Variables  A static local variable has the visibility of an automatic local variable (that is, inside the function containing it).  However, its lifetime is the same as that of a global variable, except that it doesn’t come into existence until the first call to the function containing it.  Thereafter it remains in existence for the life of the program.  Static local variables are used when it’s necessary for a function to remember a value when it is not being executed; that is, between calls to the function.
  • 56. Example #include <iostream> using namespace std; float getavg(float); //declaration int main() { float data=1, avg; while( data != 0 ) { cout << “Enter a number: “; cin >> data; avg = getavg(data); cout << “New average is “ << avg << endl; } return 0; } //-------------------------------------------------------------- float getavg(float newdata) { static float total = 0; //static variables are initialized static int count = 0; // only once per program count++; //increment count total += newdata; //add new data to total return total / count; //return the new average }
  • 57. Static variables  Initialization: When static variables are initialized, as total and count are in getavg() , the initialization takes place only once—the first time their function is called. They are not reinitialized on subsequent calls to the function, as ordinary local variables are.  Storage: local variables and function arguments are stored on the stack, while global and static variables are stored on the heap.