Functions and scope in C++
This module explores the syntax, use, and scope of C++ functions and variables. Functions are very similar in C and C++, but C++ offers some useful improvements, including
overloading and inlining.
C++ also offers storage classes similar to those of C, which are essential in writing multifile programs.
You will learn:
- How C++ uses function prototypes
- How using default function arguments can save you time
- What it means to overload a function
- How to use the keyword
inline to speed up programs
- The difference between file scope and local scope
- How the
static storage classes are useful in multifile programs
- The rules of linkage for multifile programs
- What namespaces are and why they are useful
At the end of the module, you will be given the opportunity to take a quiz covering these topics.
Purpose of C++ Functions
The main way of getting something done in a C++ program is to call a function to do it. Defining a function is the way you specify how an operation is to be done and a function cannot be called unless it has been previously declared.
A function declaration gives
- the name of the function,
- the type of the value returned (if any), and
- the number and types of the arguments that must be supplied in a call.
Elem. next_elem(); // no argument; return a pointer to Elem (an Elem*)
void exit(int); // int argument; return nothing
double sqrt(double); // double argument; return a double
In a function declaration, the return type comes before the name of the function and the argument types after the name enclosed in parentheses.The semantics of argument passing are identical to the semantics of copy initialization.
That is, argument types are checked and implicit argument type conversion takes place when necessary.