How to Use Inline Variables?

It is very easy to use inline variables in C++. It is just a three-step process to declare and use inline variables in our program:

  1. First, we use the inline keyword to declare and define the variable in a header file.
  2. Now, we will include this header file and access the inline variable in the source code where we want to use the inline variable.
  3. Run the program.

Inline Variable Declaration

We can easily declare a variable as inline by using the keyword inline before the normal declaration and we can also assign value to the variable with the help of the regular assignment operator.

head.hpp

C++




inline int inline_var = 10


Accessing the Inline Variable

An inline variable defined inside a header file can be accessed by importing that header file using #include preprocessor directive.

source.cpp

C++




// C++ program to show how to access the inline variable
// with external linkage
#include "head.hpp"
#include <iostream>
using namespace std;
  
int main()
{
    // printing the value stored inside inline variable.
    cout << inline_var;
    return 0;
}


Output

10

Inline Variables in C++ 17

An inline variable in C++ is a variable that is declared using an inline specifier. It is an exception to one definition having multiple definitions across various translation units. Inline variables have an external linkage when not declared as static.

Similar Reads

Syntax

inline data_type variable_name = initial_value;...

How to Use Inline Variables?

It is very easy to use inline variables in C++. It is just a three-step process to declare and use inline variables in our program:...

Properties of Inline Variables

...

Advantages of Using Inline Variables

...

Contact Us