Introduction to Functions
Functions are easy and complex
The basic syntax is not too difficult.
However, when to use functions and how to use them is sometimes challenging.
The why is simple: To make code easier to read.
But it is also more complex.
Chapter 4 and the beginning of chapter 8 provides the why of functions.
But I would like to discuss the how first, then the why.
So what should you read?
Chapter 8, but I am starting on 8.2
Chapter 4, 4.6 on, but especially 4.7
I also assume you did
homework 8
.
Functions are difficult because they are open and flexible.
But all functions have several things in common:
The function must be
declared
before it is used.
In modern c++ this is done with a
function prototype
These are declared before the main function.
The function must be
defined
This is the function prototype plus the actual code for the function.
This is usually placed
after
the main function.
Functions are then called
This can be done anywhere after the function is declared.
In the main or in other functions.
Even in the function itself. (But do not do this yet)
Function prototypes
In c/c++ function prototypes have
A return type, possibly
void
A function name, an identifier
A list of 0 or more parameters
By EUP convention, function names
Start with an upper case letter.
Each word starts with an upper case letter.
ReadAWord OpenTheFile ComputeAverageIncome
I like the function names to describe what the function does.
Parameters
Are ways to pass data into/out of a function.
They have a type.
They have a changeability
If we don't want to change it we
pass by value.
If we do want to change it we
pass by reference.
They have an identifier.
All data needed in a function should be passed as a parameter.
WE DO NOT USE GLOBAL VARIABLES.
WE DO NOT USE STATIC VARIABLES.
We will discuss this much more in the future.
Return value
This is nearly any c/c++ type
But is not required, it can be
void
Function declaration
This includes the function prototype.
But also includes code
This is just like main
You may have
local variables
You will have executable code
You should/may have a return statement.
Function calls
Include arguments
These must match the parameters in
Number of arguments/parameters
type of the arguments/parameters
variability of the arguments/parameters
You can pass a constant into a reference parameter.
Flow of control
When a function is called:
Flow of control passes to the
called
function.
The code in the function is executed
Then the flow of control returns
calling
function immediately after the function call.