Lecture 14 Functions
Lecture 14 Functions
Functions
CS100 – Lecture # 14
Fall 2016
SBASSE, LUMS
Goals of this module
1. Functions in C++ (5.1 till 5.5)
2. Creating functions
3. Calling functions
2
Pre-defined functions
• Where did these predefined functions came from?
• #include<cmath>
3
Remember the fun with cmath?
4
Understanding the program
control flow
• Consider the example:
5
6
Things required to write a function
• When writing this function, you need to
1. Pick a name for the function (pow). <-Same as identifier
7
Anatomy of a function
8
Syntax of a function
• Two step process!
2. Function definition
• Describes how the function does its task
• Can appear before or after the function is called
• If appears after the function is called, then a function declaration before the call is required
• Syntax:
Return_Type Function_Name(Parameter1_Type Parameter1_Name, …)
{
//code to make the function work
}
9
Function Definition
• Declaration provides the footprint while definition provides the
implementation
function header
Example:
function body
10
11
The Return Statement
• Ends the function call
• Syntax:
return expression;
• expression performs the calculation
or
• expression is a variable containing the
calculated value
• Example:
return subtotal + subtotal * TAX_RATE;
The Function Call
• Tells the name of the function to use
• Example:
double bill = total_cost(number, price);
Function Call Details
• The values of the arguments are plugged into the formal
parameters
15
http://www.bogotobogo.com/cplusplus/stackunwinding.php
Alternate Declarations
• Two forms for function declarations
• List formal parameter names
• List types of formal parmeters, but not names
• First aids description of the function in comments
• Examples:
double total_cost(int number_par, double price_par);
• Compiler cannot check that arguments are in the correct logical order
• Produces a faulty result because the arguments are not in the correct
logical order. The compiler will not catch this!
Function Definition Syntax
• As you did in the “main” function, within a user-
defined function definition
AND / OR
• Pointers
• Structures
26