0% found this document useful (0 votes)
14 views

CPP Slide3.3

Functions in C++ can be user-defined or built-in. Functions must be declared before use with a prototype specifying return type and parameters. A function definition defines how the function works through a header specifying parameters and a body enclosing declarations and statements. Functions have their own scope, and variables can be local or global depending on whether they are declared inside or outside of functions.

Uploaded by

Solomon Desalegn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CPP Slide3.3

Functions in C++ can be user-defined or built-in. Functions must be declared before use with a prototype specifying return type and parameters. A function definition defines how the function works through a header specifying parameters and a body enclosing declarations and statements. Functions have their own scope, and variables can be local or global depending on whether they are declared inside or outside of functions.

Uploaded by

Solomon Desalegn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Functions in C++

 Function - a subprogram that can act on data and return


a value
 Every C++ program has at least one function, main(),
where program execution begins
 A C++ program might contain more than one function.
 Functions may interact using function call
 Functions in C++ come in two varieties:

 user-defined

 built-in
 E.g pow(), sqrt(), cin, etc

1 by Desalegn 11/21/2017
Declaration of Functions
 Functions must be declared before use
 The declaration tells the compiler
 The name,
 Return type,
 Parameters of the function
 Three ways
 Write your prototype into a file, and then use the
#include directive to include it in your program.
 Write the prototype into the file in which your
function is used.
 Define the function before it is called by any other
function.
2 by Desalegn 11/21/2017
Function Prototypes
 The declaration of a function is called its prototype
 Is a statement - it ends with a semicolon
 It consists of the function's
 return type,
 name,
 parameter list
 Syntax
 return_type function_name (type [parameterName1],
type [ParameterName2] ... );
 E.g. long Area(int, int);
Or
long Area(int length, int width);

3 by Desalegn 11/21/2017
Function Prototypes
 All functions have a return type – default is int
 If the function doesn’t have a return type void will be used
 void is a reserved word
 The function prototype usually placed at the beginning of
the program
 The definition of the prototype must be given
 Many of the built-in functions have their function
prototypes already written in the header files you include
in your program by using #include

4 by Desalegn 11/21/2017
Defining a Function
 The definition tells the compiler how the function works.
 Consists of :
 the function header :
 like the function prototype except that the parameters
must be named
 there is no terminating semicolon
 its body
 the task of the function
 Syntax
return_type function_name(parameter declarations)
{
declarations;
statements;
}
5 by Desalegn 11/21/2017
Defining a Function
 E.g.
long Area(long l, long w)
{
return l * w;
}
 The return statement without any value is typically
used to exit the function early
 C++ does not allow nested functions
 The definition of one function cannot be included in
the body of another function
 A function definition must agree in return type and
parameter list with its prototype
6 by Desalegn 11/21/2017
Defining a Function
 If the function returns a value, it’s definition should
end with a return statement
 The body of the function is always enclosed in braces,
even when it consists of only one statement
 return keyword
 Returns data, and control goes to function’s caller
 If no data to return, use return;
 Function ends when reaches right brace
 Control goes to caller

7 by Desalegn 11/21/2017
Program Using a Function
#include <iostream>
using namespace std;
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<"enter the temperature"<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<"the corresponding Fahrenheit is"<<result<<endl;
}
double Celsius_to_Fahr(double Celsius)
{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
8 by }
Desalegn 11/21/2017
Execution of Functions
 Each function has its own name
 When that name is encountered, called function call,
the execution of the program branches to the body of
that function – called function
 When the function returns, execution resumes on the
next line of the calling function
 Functions can also call other functions and can even
call themselves

9 by Desalegn 11/21/2017
Scope of identifier
 Refers to where in the program an identifier is
accessible
 Determines how long it is available to your program
and where it can be accessed
 Two kind
 Local identifier - identifiers declared within a
function (or block)
 Global identifier – identifiers declared outside of
every function definition

10 by Desalegn 11/21/2017
Local scope
 You can declare variables within the body of the function
 local variables
 When the function returns, the local variables are no
longer available
 Variables declared within a block are scoped to that block
– Local to that block
 they can be accessed only within that block and "go
out of existence" when that block ends
 E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
11 by Desalegn 11/21/2017
Global Scope
 Variables defined outside of any function have global
scope
 Available from any function in the program, including
main()
 A local variable with the same name as a global
variable hides the global variable - when used within
the function

12 by Desalegn 11/21/2017
#include <iostream> void myFunction()
using namespace std; {
void myFunction(); // prototype int y = 10;
int x = 5, y = 7; // global variables cout << "x from myFunction: " << x <<
"\n";
int main()
cout << "y from myFunction: " << y <<
{ "\n\n";
cout << "x from main: " << x << }
"\n";
Output: x from main: 5
cout << "y from main: " << y <<
y from main: 7 x from myFunction: 5
"\n\n";
y from myFunction: 10
myFunction();
Back from myFunction!
cout << "Back from
myFunction!\n\n"; x from main: 5
cout << "x from main: " << x << y from main: 7
"\n";
cout << "y from main: " << y <<
"\n";
return 0;}

13 by Desalegn 11/21/2017
Unary Scope Resolution Operator ::
 Using ::, one can access an global variable even if it is
over-shadowed by a local variable of the same name.
 E.g
void func1()
#include <iostream>
{
using namespace std;
float num=10;
void func1();
cout<<"the value of num in func1
void func2();
is:"<<::num<<endl;
float num=10.8;
}
int main()
void func2()
{
{
func1();
float num=10;
func2();
cout<<"the value of num in func2
return 0;
is:"<<num<<endl;
}
}
14 by Desalegn 11/21/2017
Storage class
 Storage class determines the period during which an identifier exists
in memory
 Four storage classes
 auto
 Local variables in functions or blocks. Auto storage class
variables are created only when the block is active, and
disappear when the block or function exits.
 register
 Variable existence like auto. The register variable is a
suggestion to the compiler to put the variable in a CPU register.
 static
 Local static variable exists during the whole program executing,
i.e., the variable retains its value between function calls.
 However, the reference to the variable is local in the function or
block
 extern
 Global variables and function names have the storage class
extern. Extern storage class variable exists during the whole
program execution.
15 by Desalegn 11/21/2017
Storage class and variables
 Automatic variable - memory is allocated at block entry
and deallocated at block exit
 Static variable - memory remains allocated as long as the
program executes
 Retain their values across function calls.
 Variables declared outside of any block are static
variables
 By default, variables declared within a block are
automatic variables
 Declare a static variable within a block by using the
reserved word static

16 by Desalegn 11/21/2017
Static and Automatic Variables cont…
 The syntax for declaring a static variable is:
static dataType identifier;
 E.g.
static int x;
 declares x to be a static variable of the type int
 Static variables declared within a block are local
to the block
 Their scope is the same as any other local
identifier of that block

17 by Desalegn 11/21/2017
Functions with Default Parameters
 When a function is called
 The number of actual and formal parameters must be
the same
 C++ relaxes this condition for functions with default
parameters
 You specify the value of a default parameter when the
function name appears for the first time, such as in the
prototype

18 by Desalegn 11/21/2017
Functions with Default Parameters cont…
 If you do not specify the value of a default parameter
 The default value is used
 All of the default parameters must be the rightmost
parameters of the function
 In a function call where the function has more than one
default parameter and a value to a default parameter is
not specified
 You must omit all of the arguments to its right
 Default values can be constants, global variables, or
function calls
 The caller has the option of specifying a value other
than the default for any default parameter
 You cannot assign a constant value as a default value to
19 a reference
by Desalegn parameter 11/21/2017
Empty Parameter Lists
 functions can take no arguments
 To declare that a function takes no parameters:
 Write void or nothing in parentheses
 E.g
 void print1( void );
 void print2();

20 by Desalegn 11/21/2017
Parameter Passing
 Call by Value
 Value of the function argument passed to the
formal parameter of the function
 Copy of data passed to function
 Changes to copy do not change original
 Call by Reference
 Address of the function argument passed to the
formal parameter of the function

21 by Desalegn 11/21/2017
Call by Value Example
//function to swao two values
void swap(int a, int b)
{
int hold;
hold = a;
a = b;
b = hold;
return;
}
22 by Desalegn 11/21/2017
Function Overloading
 Function overloading
 Functions with same name and different
parameters
 Should perform similar tasks
 I.e., function to square ints and function to
square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
 A call-time c++ complier selects the proper
function by examining the number, type and order
of the parameters
23 by Desalegn 11/21/2017
Functions and Structure
struct StudentRecord {
string name; // student name
double hw[3]; // homework grades
double test[2]; // test grades
double ave; // final average

void print_ave() {
cout << "Name: " << name << endl;
cout << "Average: " << ave << endl;
}
};
24 by Desalegn 11/21/2017
Using the member function
StudentRecord stu1;

… // set values in the structure

stu1.print_ave();

25 by Desalegn 11/21/2017

You might also like