-
Syntax, Use, and Scope of C++ Functions and Variables
-
Inlining in C++
Example of an Inline Function:
inline int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 10); // The compiler may replace this with `int result = 5 + 10;`
return 0;
}
Summary:
- Functions in C++ are similar to those in C, but C++ offers enhancements like overloading and inlining for better performance and flexibility.
- The
inline
keyword suggests to the compiler to replace function calls with the function’s body, but the compiler can decide whether to honor this request based on optimization strategies.
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.
- Module Objectives 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
extern
and 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.
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.