Loading lessons...
Inline Functions & Default Parameter Values
Inline Functions & Default Parameter Values
Two C++ features make functions cheaper and easier to call. An inline function removes the overhead of calling a small function. Default arguments let a caller leave out arguments that usually have the same value.
1. The Cost of a Function Call
Every call to a function involves work besides the function's own code: jumping to the function, saving registers, pushing arguments onto the stack, and returning. For a large function this overhead is negligible. For a one-line function, such as cube(x), the overhead can take longer than the work itself.
C solves this with macros (#define), but macros are plain text substitution: they are not real functions, so the compiler does no type checking, and they misbehave with expressions.
2. Inline Functions
An inline function is a function whose code is expanded in place of each call by the compiler, like a macro, but it remains a true function with type checking and normal argument evaluation.
#include <iostream>
using namespace std;
inline float cube(float x) {
return x * x * x;
}
inline int maxOf(int a, int b) {
return (a > b) ? a : b;
}
int main() {
cout << "cube(3) = " << cube(3) << endl;
cout << "cube(1.5) = " << cube(1.5) << endl;
cout << "maxOf(12, 9) = " << maxOf(12, 9) << endl;
return 0;
}Output:
cube(3) = 27
cube(1.5) = 3.375
maxOf(12, 9) = 12The compiler may replace cube(3) with 3 * 3 * 3, so no call takes place.
Inline is only a request
inline is a request to the compiler, not a command. The compiler may ignore it and compile a normal call, typically when:
- the function contains a loop,
switchorgoto; - the function is recursive;
- the function contains static variables;
- a function returning a value has a
returnstatement that is not reached on every path, or the function is simply too large; - the function's address is taken (through a function pointer).
All member functions defined inside a class body are inline automatically (Lesson 13).
Macro vs inline function
The classic trap with a macro: its argument is pasted as text, so it may be evaluated twice and operator precedence can break it.
#include <iostream>
using namespace std;
#define SQUARE(x) x* x // macro: text substitution
inline int square(int x) {
return x * x;
} // inline function
int main() {
int a = 3;
cout << "SQUARE(a + 1) = " << SQUARE(a + 1) << endl; // becomes a + 1 * a + 1
cout << "square(a + 1) = " << square(a + 1) << endl; // (a + 1) is evaluated once
return 0;
}Output:
SQUARE(a + 1) = 7
square(a + 1) = 16SQUARE(a + 1) expands to a + 1 * a + 1, which is 3 + 3 + 1 = 7, not 16.
Macro (#define) | Inline function |
|---|---|
| handled by the preprocessor | handled by the compiler |
| plain text substitution | real function semantics |
| no type checking of arguments | arguments are type-checked |
| arguments may be evaluated more than once | each argument is evaluated once |
| precedence problems unless fully bracketed | no precedence problems |
| cannot access private members of a class | can be a member function |
| cannot be debugged step by step | can be debugged like a function |
Advantages and disadvantages of inline functions
| Advantages | Disadvantages |
|---|---|
| no function-call overhead, so faster for small functions | the code is copied at every call, so the executable grows |
| type safe, unlike macros | a larger program may cause more cache misses, slowing things down |
| the compiler can optimise the expanded code with its surroundings | changing an inline function means recompiling every file that uses it |
| not suitable for large or recursive functions |
Rule of thumb: make a function inline only if it is small (one to three lines) and called often.
3. Default Arguments (Default Parameter Values)
C++ lets a function be called without specifying all its arguments. The missing arguments take default values given in the prototype.
float amount(float principal, int period, float rate = 0.15);A call amount(5000, 7) uses rate = 0.15; amount(5000, 5, 0.12) overrides it with 0.12.
Rules
- Defaults are written in the prototype (or in the definition only if there is no separate prototype), not in both.
- Defaults must be supplied from right to left: once an argument has a default, every argument to its right must have one too.
- On a call, arguments are matched left to right; you cannot skip a middle argument and give a later one.
- A default value can be a constant, a global variable or an expression (even a function call).
| Prototype | Valid? | Why |
|---|---|---|
int mul(int i, int j = 5, int k = 10); | ✅ | defaults on the rightmost arguments |
int mul(int i = 5, int j); | ❌ | j has no default but is to the right of one |
int mul(int i = 0, int j, int k = 10); | ❌ | j breaks the right-to-left rule |
int mul(int i = 2, int j = 5, int k = 10); | ✅ | all have defaults |
#include <iostream>
using namespace std;
// prototype with two default arguments
float amount(float principal, int period = 1, float rate = 0.10);
void printLine(char ch = '-', int len = 30);
int main() {
printLine(); // '-' and 30
cout << "amount(1000) = " << amount(1000) << endl; // 1 year, 10%
cout << "amount(1000, 2) = " << amount(1000, 2) << endl; // 2 years, 10%
cout << "amount(1000, 2, .2) = " << amount(1000, 2, 0.2) << endl; // 2 years, 20%
printLine('='); // '=' and 30
printLine('*', 10);
return 0;
}
// compound interest; the defaults are NOT repeated here
float amount(float principal, int period, float rate) {
float value = principal;
for (int year = 1; year <= period; year++) {
value = value * (1 + rate);
}
return value;
}
void printLine(char ch, int len) {
for (int i = 0; i < len; i++) {
cout << ch;
}
cout << endl;
}Output:
------------------------------
amount(1000) = 1100
amount(1000, 2) = 1210
amount(1000, 2, .2) = 1440
==============================
**********Advantages of default arguments
- A function can be called with fewer arguments when the usual values are fine.
- New parameters can be added to an existing function without changing the existing calls (give the new parameter a default).
- They can replace several overloaded functions with one:
printLine(),printLine('=')andprintLine('*', 10)all use one definition.
Default arguments and overloading can clash. With void f(int a, int b = 0); and void f(int a); both declared, the call f(5) is ambiguous and will not compile.
Key points to remember
inlineasks the compiler to expand the body at each call; it is a request, ignored for loops, recursion, static variables or large bodies.- Inline functions beat macros: type checking, single evaluation of arguments, no precedence traps.
- Member functions defined inside a class are automatically inline.
- Default arguments go in the prototype, from right to left; calls fill arguments from left to right.
f(5)is ambiguous if bothf(int)andf(int, int = 0)exist.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is an inline function? When does the compiler ignore the inline request? Compare inline functions with macros. (10 Marks)
- Write: the definition, the
cubeprogram, the five situations, theSQUARE(a + 1)example and the comparison table. - Q2. What are default arguments? State the rules with valid and invalid prototypes, and write a program. (5 Marks)
- Write: the four rules, the prototype table, and the
amountprogram with output. - Q3. Give the advantages and disadvantages of inline functions. (2.5 Marks)
- Q4. Which of these prototypes are valid?
int f(int a = 1, int b);andint f(int a, int b = 1);(2.5 Marks)