CSC166 ยท 2079 ยท 5 marks
What is inline function? Why it is used? Write a program to illustrate inline function.
What is inline function? Why it is used? Write a program to illustrate inline function. [5]
Quick answer
An inline function is a C++ enhancement feature in which the compiler replaces the function call with the actual body (definition) of the function at compile time, instead of making a regular function call at runtime.
Inline Function in C++
Definition
To declare an inline function, the keyword inline is placed before the function definition.
Syntax:
inline return_type function_name(parameters) {
// function body
}
Why Inline Functions are Used
As stated in the notes:
"The inline functions are a C++ enhancement feature to increase the execution time of a program. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime."
The main reasons for using inline functions are:
- To increase execution speed: Eliminates the overhead of a function call (saving/restoring registers, jumping to function address, etc.)
- To avoid function call overhead: The function body is directly substituted at the point of call during compilation.
- Useful for small, frequently called functions: Where the overhead of a call is significant compared to the function body itself.
- Maintains readability: Code remains modular and readable like normal functions, but executes like direct code.
Program to Illustrate Inline Function
#include<iostream>
using namespace std;
// Inline function to calculate square of a number
inline int square(int x) {
return x * x;
}
// Inline function to calculate cube of a number
inline int cube(int x) {
return x * x * x;
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
// Compiler replaces these calls with actual code at compile time
cout << "Square of " << num << " = " << square(num) << endl;
cout << "Cube of " << num << " = " << cube(num) << endl;
return 0;
}
Sample Output
Enter a number: 4
Square of 4 = 16
Cube of 4 = 64
How It Works
When the compiler encounters square(num), instead of making a function call at runtime, it substitutes the code as:
// square(num) is replaced by:
num * num
This substitution happens at compile time, making execution faster by removing function call overhead.
Key Points to Remember
| Feature | Inline Function |
|---|---|
| Keyword used | inline |
| Substitution time | Compile time |
| Purpose | Increase execution speed |
| Best used for | Small, frequently called functions |
| Overhead removed | Function call overhead |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.