What are __FILE__, __LINE__, and __FUNCTION__ in C++


Here we will see what are the __FILE, __LINE__ and __FUNCTION__ in C++.

The __FILE__

This macro is used to get the path of the current file. This is useful when we want to generate log files. The following code will explain its functionality.

Example

#include<iostream>
using namespace std;
int errorLog (const char* file, const std::string& msg){
   cerr << "[" << file << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FILE__, msg )
main() {
   LOG("This is a dummy error");
}

Output

[D:\Misc C and C++ Questions\test_prog.cpp] This is a dummy error

The __LINE__

This macro can find the current line number in source file. This line number is an integer value. When log statements are generating then __LINE__ plays some useful role. See the following example to get the idea.>

Example

#include<iostream>
using namespace std;
int errorLog (int line, const std::string& msg){
   cerr << "[" << line << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __LINE__, msg )
main() {
   LOG("This is a dummy error");
}

Output

[12] This is a dummy error

The __FUNCTION__

This macro can return the current function. When log statements are generating then __FUNCTION__ plays some useful role. See the following example to get the idea.

long double rintl(long double argument)

Example

#include<iostream>
using namespace std;
int errorLog (const char* func, const std::string& msg){
   cerr << "[" << func << "] " << msg << endl;
}
#define LOG( msg ) errorLog( __FUNCTION__, msg )
void TestFunction(){
   LOG("Send from Function");
}
main() {
   TestFunction();
   LOG("This is a dummy error");
}

Output

[TestFunction] Send from Function
[main] This is a dummy error

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements