Standard Predefined Macros
Contents
Standard Predefined Macros
C exposes a plethora of predefined macros which can be very useful in our day-to-day coding.
Also, we do encounter a few simple interview questions along these lines.
Most common ones are: How do we print the line number in a program or the file name?
Following are few of the macros and a demonstration of how they can be used:
__LINE__
This macro expands to an integer value that specifies the current executing line number.
__FILE__
This macro expands to a string constant that specifies the name of the current executing file.
__func__
This macro expands to a string constant that specifies the name of the current executing function.
The above macros can be used as a part of debugging any errors in a particular part of the program. It eliminates the need to write multiple debug messages. Also, it eliminates the problem of keeping any debug prints updated as code is modified.
#include <iostream>
using namespace std;
void test_standard_predefined_macros();
int main()
{
test_standard_predefined_macros();
return 0;
}
void test_standard_predefined_macros()
{
cout << "File: " << __FILE__ << endl;
cout << "Function: " << __func__ << endl;
cout << "Line: " << __LINE__ << endl;
}
Output:
File: ../testPredefinedMacros.cpp
Function: test_standard_predefined_macros
Line: 18
Few other standard predefined macros are:
__TIME__
The macro expands to a string constant that specifies the time at which it is being run.
__DATE__
The macro expands to a string constant that specifies the date on which it is being run.