This post will discuss how to find the current line number in C++.

1. Using __LINE__ Macro

The standard solution to find the current line number in C++ is using the predefined macro __LINE__. It returns the integer value representing the current line in the source code file being compiled.

Download  Run Code

 
The preprocessor will simply replace the __LINE__ macro with the current line number. This might cause undesired results when used within a function, as shown below.

Download  Run Code

 
To print the line number of the caller function, we have to pass __LINE__ as a function argument.

Download  Run Code

2. Using std::experimental::source_location

The std::experimental::source_location class represents certain information about the source code, such as file names, line numbers, and function names. The source_location class is defined in the header <experimental/source_location> and provides a better alternative to macros.

 
The current() function constructs a new source_location object and line() function to returns the line number represented by it. It can be used as follows:

Download  Run Code

 
To print the line number of the caller function, we can use the current() function as a default argument.

Download  Run Code

3. Using std::source_location

If your compiler supports C++20, then the new standard <source_location> header is a better alternative. With C++20, the std::experimental::source_location was merged into the mainline ISO C++ standard as std::source_location. All its member functions and usage remains the same.

Download Code

That’s all about finding the current line number in C++.