This chapter covers two small features that make functions more convenient to use. Both appear constantly in real C++ code and in interviews, and both are often misunderstood.
Default arguments let a caller leave out arguments that usually have the same value.
Inline functions have a famous textbook meaning ("the compiler pastes the body at the call site") and a rather different modern meaning ("this function may be defined in a header"). We will learn both, and see which one actually matters today.
We build directly on the Functions and Function Overloading chapters.
Default Arguments
Think of ordering tea at a stall. Unless you say otherwise, you get regular sugar and a normal cup. You only mention the details when you want something different. Default arguments bring the same idea to function calls.
A default argument is a value given to a parameter in the function declaration. If the caller does not pass an argument for that parameter, the compiler automatically uses the default value.
#include <iostream>
#include <string>
void greet(std::string name, std::string greeting = "Hello") {
std::cout << greeting << ", " << name << "!\n";
}
int main() {
greet("Asha"); // uses the default "Hello"
greet("Ravi", "Namaste"); // overrides the default
}
Output:
Hello, Asha!
Namaste, Ravi!
There is only one function here. For the call greet("Asha"), the compiler silently rewrites it as greet("Asha", "Hello"). That is the key idea: default arguments are filled in at the call site, at compile time, by the compiler.
Several Default Arguments
#include <iostream>
double simpleInterest(double principal, double rate = 7.5, int years = 1) {
return principal * rate * years / 100;
}
int main() {
std::cout << simpleInterest(10000) << '\n'; // rate 7.5, years 1
std::cout << simpleInterest(10000, 9) << '\n'; // years 1
std::cout << simpleInterest(10000, 9, 3) << '\n'; // nothing defaulted
}
Output:
750
900
2700
Arguments are matched to parameters left to right. There is no way to skip rate and give only years: simpleInterest(10000, , 3) is not valid C++. That leads to the main rule.
Rule 1: Defaults Must Be at the End (Trailing)
Once a parameter has a default, every parameter after it must also have one.
void book(int seats = 1, int coach) {} // error
error: default argument missing for parameter 2 of 'void book(int, int)'
note: ...following parameter 1 which has a default argument
Why? Since arguments fill parameters from the left, a call book(4) would set seats = 4, leaving coach with nothing. Putting defaults at the end guarantees that leaving out arguments from the right always works. So: put the parameters most likely to be defaulted last.
Declaration | Valid? |
|---|---|
| Yes |
| Yes (can be called with 0 to 3 arguments) |
| No: |
| No |
Rule 2: Specify the Default Once, Usually in the Declaration
The default must be visible where the function is called, because the compiler fills it in at the call. When you use a prototype (or a header file), put the defaults there, and do not repeat them in the definition:
#include <iostream>
// Declaration: defaults go here, where callers can see them
void drawBox(int width, int height = 2, char ch = '#');
int main() {
drawBox(5);
drawBox(3, 1, '*');
}
// Definition: defaults are NOT repeated
void drawBox(int width, int height, char ch) {
for (int r = 0; r < height; ++r) {
for (int c = 0; c < width; ++c) std::cout << ch;
std::cout << '\n';
}
}
Output:
#####
#####
***
Repeating the default, even with the same value, is an error:
void drawBox(int width, int height = 2);
void drawBox(int width, int height = 2) {}
error: default argument given for parameter 2 of 'void drawBox(int, int)' [-fpermissive]
note: previous specification in 'void drawBox(int, int)' here
A common style is to write the default as a comment in the definition, e.g. void drawBox(int width, int height /* = 2 */, char ch /* = '#' */), so readers of the .cpp file still see it.
Rule 3: Default Expressions Are Evaluated at Each Call
A default does not have to be a constant. It can be any expression (a global variable, a function call), and it is evaluated every time the default is actually used:
#include <iostream>
int defaultQuantity = 1;
int nextId() {
static int id = 100;
return ++id;
}
void order(int qty = defaultQuantity, int id = nextId()) {
std::cout << "order #" << id << " qty " << qty << '\n';
}
int main() {
order();
defaultQuantity = 5; // the default expression is re-evaluated per call
order();
order(2, 999); // explicit arguments: nextId() is NOT called
order();
}
Output:
order #101 qty 1
order #102 qty 5
order #999 qty 2
order #103 qty 5
Two things to notice: changing defaultQuantity changed the default for later calls, and nextId() was not called at all for order(2, 999) (otherwise the last ID would be 104). Note that names in a default argument are looked up where the function is declared, not where it is called, so the caller's local variables are never visible there; and a default argument may not use the function's other parameters (void f(int a, int b = a); is an error).
Python programmers, take note: in Python a default value is created once, when the function is defined. In C++ the default expression is evaluated afresh at every call that uses it.
Default Arguments vs Function Overloading
Default arguments can replace a group of overloads that only differ by "with or without the last few parameters":
Overloading: Default arguments:
void greet(std::string name); void greet(std::string name,
void greet(std::string name, std::string greeting = "Hello");
std::string greeting); → one function, one body
But mixing the two carelessly creates ambiguity:
#include <iostream>
void print(int a) { std::cout << a << '\n'; }
void print(int a, int b = 0) { std::cout << a << ' ' << b << '\n'; }
int main() {
print(5, 6); // fine: only the 2-parameter version fits
print(5); // which one?
}
error: call of overloaded 'print(int)' is ambiguous
note: candidate 1: 'void print(int)'
note: candidate 2: 'void print(int, int)'
Both functions can be called with one int and both are exact matches, so neither wins (see overload resolution in Function Overloading). Interestingly, the declarations themselves are legal; the error only appears when someone makes the ambiguous call.
Use default arguments when… | Use overloading when… |
|---|---|
the logic is the same and only some values usually stay the same | the logic differs for different types or numbers of inputs |
you want one body to maintain | parameters have different types, not just "missing" ones |
the omitted parameters are at the end | you need to "skip" a middle parameter |
Inline Functions
The Classic Idea: Avoiding Call Overhead
From the Functions chapter you know that each call creates a stack frame: arguments are copied, the return address is saved, the program jumps to the function and back. For a tiny function like square(x), this bookkeeping can cost more than the actual multiplication.
Inlining is an optimization where the compiler replaces the call with the function's body:
Source: After inlining (conceptually):
int y = square(a + 1); → int t = a + 1;
int y = t * t; // no call, no jump
Traditionally, C++ books say: "mark a function inline to ask the compiler to do this."
inline int square(int x) {
return x * x;
}
This was only ever a request. And modern compilers have become far better than humans at deciding what to inline. They:
may ignore
inline(for example, for a large or recursive function), andmay inline functions that are not marked
inlineat all, when optimization is on.
You can see this with g++ and nm (which lists the functions present in the program):
#include <iostream>
inline int cube(int x) { return x * x * x; }
int main(int argc, char**) {
std::cout << cube(argc + 1) << '\n';
}
$ g++ -std=c++23 -O0 opt.cpp && nm -C a.out | grep cube
00000000000011b0 W cube(int) ← -O0: a real function, really called
$ g++ -std=c++23 -O2 opt.cpp && nm -C a.out | grep cube
← -O2: nothing, the body was inlined into main
(Run with no command-line arguments, argc is 1, so the program prints 8 in both builds.) Without optimization, inline did not cause any inlining. With -O2, the compiler inlined the call, and would have done so even without the keyword.
The Modern Meaning: "May Be Defined in More Than One File"
So what is inline really for today? It changes a linking rule. Recall the One Definition Rule (ODR): a normal function must be defined exactly once in the whole program. Suppose you put a small helper's definition in a header:
// mathutil.h
#pragma once
int twice(int x) { // NOT inline: a definition in a header
return 2 * x;
}
// a.cpp
#include "mathutil.h"
int fromA() { return twice(10); }
// main.cpp
#include <iostream>
#include "mathutil.h"
int fromA();
int main() {
std::cout << fromA() + twice(1) << '\n';
}
Compiling both files together with g++ -std=c++23 a.cpp main.cpp (temporary object-file names removed):
main.cpp:(.text+0x0): multiple definition of `twice(int)'; a.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
#pragma once (or an include guard) does not help: it prevents including a header twice within one .cpp file, but each .cpp file is compiled separately, so both object files contain a definition of twice, and the linker finds two.
Now add one word:
// mathutil.h
#pragma once
inline int twice(int x) { // inline: the same definition may appear in many .cpp files
return 2 * x;
}
Output:
22
In modern C++,
inlinemeans: this function (or, since C++17, variable) may be defined in several translation units, as long as every definition is identical. The linker keeps one copy. Whether calls are actually inlined is the optimizer's decision.
Rules that come with it:
The definition must be visible in every file that calls it, which is why inline functions live in headers.
All definitions must be token-for-token identical. If two files see different bodies, the program is ill-formed, no diagnostic required: the compiler and linker usually say nothing, and the program may silently use either body (in practice, it behaves like undefined behaviour).
An inline function still has a single address;
&twiceis the same in every file.
Things That Are Implicitly Inline
Entity | Implicitly inline since |
|---|---|
Member function defined inside a class body | C++98 (see Classes & Objects); not inside a C++20 named module |
| C++11 |
| C++20 |
| C++17 |
Function templates are not "inline" by default, but they have a similar exemption from the one-definition rule, so they can also be defined in headers (see Templates).
Inline Variables (C++17)
Before C++17, sharing one global constant object across files needed a declaration in a header and a definition in exactly one .cpp. C++17 allows inline on variables:
#include <iostream>
inline int cube(int x) { return x * x * x; }
constexpr int MAX_STUDENTS = 60; // const at namespace scope: internal linkage
inline constexpr double GST_RATE = 0.18; // C++17 inline variable: one shared object
int main() {
std::cout << cube(4) << '\n';
std::cout << MAX_STUDENTS << ' ' << GST_RATE << '\n';
}
Output:
64
60 0.18
Both constants can safely go in a header. The difference: a namespace-scope const/constexpr variable has internal linkage, so every .cpp file gets its own copy; an inline variable is one object shared by the whole program. For simple numbers this rarely matters, but for larger objects, or when addresses are compared, inline constexpr is the modern recommendation for header constants.
Inline Functions vs Macros
C programmers used #define macros to avoid call overhead. A macro is plain text substitution done by the preprocessor before compilation, and that causes nasty surprises:
#include <iostream>
#define SQUARE(x) x * x
inline int square(int x) {
return x * x;
}
int main() {
std::cout << "SQUARE(1 + 2) = " << SQUARE(1 + 2) << '\n'; // 1 + 2 * 1 + 2
std::cout << "square(1 + 2) = " << square(1 + 2) << '\n';
std::cout << "100 / SQUARE(5) = " << 100 / SQUARE(5) << '\n'; // 100 / 5 * 5
std::cout << "100 / square(5) = " << 100 / square(5) << '\n';
}
Output:
SQUARE(1 + 2) = 5
square(1 + 2) = 9
100 / SQUARE(5) = 100
100 / square(5) = 4
SQUARE(1 + 2) expands to 1 + 2 * 1 + 2, which is 5. 100 / SQUARE(5) becomes 100 / 5 * 5, which is 100. Even the "fixed" macro #define SQUARE(x) ((x) * (x)) still evaluates its argument twice, so SQUARE(i++) modifies i twice in one expression: undefined behaviour. A function evaluates each argument exactly once, so none of this can happen.
Feature | Macro ( | Inline function |
|---|---|---|
Processed by | Preprocessor (text replacement) | Compiler |
Type checking | None | Full, like any function |
Arguments evaluated | As many times as they appear in the macro | Exactly once |
Operator precedence problems | Yes, unless fully parenthesised | No |
Respects scope / namespaces | No | Yes |
Debugging | Hard (the compiler never sees the macro name) | Normal |
Can be overloaded, can be | No | Yes |
In modern C++, use inline/constexpr functions (and templates for many types) instead of function-like macros. Keep macros for things only the preprocessor can do, such as include guards and conditional compilation.
Advantages and Disadvantages of Inlining
Whether the optimizer decides to inline or you hint at it, the trade-offs are the same:
Advantages | Disadvantages |
|---|---|
No call/return overhead for small functions | Code bloat: the body is copied at every call site, increasing program size |
Exposes the body to the optimizer at the call site, enabling further optimizations (constant folding, removing dead branches) | A larger program can use the CPU's instruction cache less efficiently, sometimes making it slower |
Lets you write small helper functions in headers without link errors | Changing an inline function in a header forces every file that includes it to be recompiled |
Functions that generally cannot be fully inlined: recursive functions (the compiler can unroll a few levels at most), and virtual functions called through a pointer or reference when the actual type is unknown at compile time. Calls through function pointers are also usually not inlined.
Guidelines:
Write small, clear functions and let the optimizer (
-O2) decide about inlining.Use the
inlinekeyword when you define a non-template function in a header. That is its real job now.Compiler-specific attributes such as GCC's
__attribute__((always_inline))or MSVC's__forceinlineexist, but they are non-standard; use them only after measuring.
Common Mistakes
Putting a default argument before a parameter without one.
Writing the default in both the declaration and the definition.
Putting the default only in the definition (in a
.cppfile) while callers in other files see a header declaration without it: those callers cannot use the default.Overloading
f(int)together withf(int, int = 0), which makesf(5)ambiguous.Believing
inlineforces inlining, or that a function withoutinlineis never inlined.Defining a non-inline function in a header that several
.cppfiles include ("multiple definition" link error).Using function-like macros instead of inline functions.
Interview and GATE Questions
Q1. Which declarations are valid? (a) void f(int a, int b = 5, int c = 6); (b) void f(int a = 1, int b, int c = 6); (c) void f(int a = 1, int b = 2);
void f(int a, int b = 5, int c = 6); (b) void f(int a = 1, int b, int c = 6); (c) void f(int a = 1, int b = 2);(a) and (c) are valid. (b) is invalid because b has no default but follows a, which does. Default arguments must be trailing.
Q2. When are default arguments evaluated, and by whom?
The compiler inserts them at the call site, at compile time, whenever a call omits those arguments. The default expression itself is evaluated at run time on every such call, so a default like = counter or = nextId() can produce different values on different calls.
Q3. Does the inline keyword guarantee that a function will be inlined?
inline keyword guarantee that a function will be inlined?No. It is at most a hint for that purpose; compilers make their own inlining decisions and may inline functions not marked inline. Its guaranteed effect is on linkage: an inline function may be defined (identically) in multiple translation units without violating the One Definition Rule.
Q4. What does #define MUL(a, b) a * b give for MUL(2 + 3, 4)? What would an inline function give?
#define MUL(a, b) a * b give for MUL(2 + 3, 4)? What would an inline function give?The macro expands to 2 + 3 * 4 = 14. An inline function int mul(int a, int b) { return a * b; } receives a = 5 and b = 4 and returns 20.
Q5. Why might a header-only helper function cause a "multiple definition" linker error, and how do you fix it?
Each .cpp that includes the header gets its own definition of the function, and a non-inline function may be defined only once in the program. Include guards do not help, since they work per translation unit. Fix it by marking the function inline (or constexpr, which implies inline), or move the definition into one .cpp and keep only a declaration in the header.
Q6. Given void f(int x, int y = 10); and void f(int x);, what happens on f(3) and f(3, 4)?
void f(int x, int y = 10); and void f(int x);, what happens on f(3) and f(3, 4)?f(3, 4) calls the two-parameter version. f(3) is a compile error: both functions are viable with an exact match, so the call is ambiguous.
Summary
Default arguments let callers omit trailing arguments; the compiler fills them in at the call site.
Defaults must be trailing, specified once (normally in the declaration), and are evaluated on each call that uses them.
Defaults can replace "missing last parameter" overloads, but mixing both can cause ambiguous calls.
Inlining replaces a call with the body. The optimizer decides when to do it, with or without the keyword.
The guaranteed meaning of
inlinetoday: the function (or C++17 variable) may be defined in several files, identically, without breaking the ODR. That is why it is used for definitions in headers.Member functions defined in a class,
constexprandconstevalfunctions are implicitly inline.Prefer inline/constexpr functions over function-like macros: type safety, single evaluation, no precedence traps.
Default arguments save the caller typing;
inlinesaves the linker from duplicate definitions. Leave the speed decisions to the optimizer.