
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
When should I write the keyword 'inline' for a function/method in C++?
In C++, the inline keyword is used in different places. To create inline variables, or inline namespace, and as well as to create inline methods or functions.
C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
Example
#include <iostream> using namespace std; inline int Max(int x, int y) { return (x > y)? x : y; } // Main function for the program int main() { cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; }
Output
Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010
- Related Articles
- When should I use the keyword ‘this’ in a Java class?
- When should I use an Inline script and when to use external JavaScript file?
- When to use an inline function in Kotlin?
- When to use inline function and when not to use it in C/C++?
- How to write inline if statement for print in Python?
- When should I use a composite index in MySQL?
- When Should I use Selenium Grid?
- Inline virtual function in C++
- When should I use MySQL compressed protocol?
- When should I use a semicolon after curly braces in JavaScript?
- When should we write our own assignment operator in C++?
- How should I prepare for a Python interview?
- When Should You See a Doctor for a Common Cold?
- When should we write our own assignment operator in C++ programming?
- Should I write my script in the body or the head of the HTML?
