Lesson 10 +30 XP

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.

texttt{inline} return-type function-name(arguments) { body }
C++
#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:

OUTPUT
cube(3)        = 27
cube(1.5)      = 3.375
maxOf(12, 9)   = 12

The 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:

  1. the function contains a loop, switch or goto;
  2. the function is recursive;
  3. the function contains static variables;
  4. a function returning a value has a return statement that is not reached on every path, or the function is simply too large;
  5. 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.

C++
#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:

OUTPUT
SQUARE(a + 1) = 7
square(a + 1) = 16

SQUARE(a + 1) expands to a + 1 * a + 1, which is 3 + 3 + 1 = 7, not 16.

Macro (#define)Inline function
handled by the preprocessorhandled by the compiler
plain text substitutionreal function semantics
no type checking of argumentsarguments are type-checked
arguments may be evaluated more than onceeach argument is evaluated once
precedence problems unless fully bracketedno precedence problems
cannot access private members of a classcan be a member function
cannot be debugged step by stepcan be debugged like a function

Advantages and disadvantages of inline functions

AdvantagesDisadvantages
no function-call overhead, so faster for small functionsthe code is copied at every call, so the executable grows
type safe, unlike macrosa larger program may cause more cache misses, slowing things down
the compiler can optimise the expanded code with its surroundingschanging 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.

C++
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

  1. Defaults are written in the prototype (or in the definition only if there is no separate prototype), not in both.
  2. Defaults must be supplied from right to left: once an argument has a default, every argument to its right must have one too.
  3. On a call, arguments are matched left to right; you cannot skip a middle argument and give a later one.
  4. A default value can be a constant, a global variable or an expression (even a function call).
PrototypeValid?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
C++
#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:

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('=') and printLine('*', 10) all use one definition.
⚠️ Warning

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

  • inline asks 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 both f(int) and f(int, int = 0) exist.
🎯 END-TERM EXAM PREP

📝 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 cube program, the five situations, the SQUARE(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 amount program 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); and int f(int a, int b = 1); (2.5 Marks)