Predefined macros in C++

Hello everybody, in this tutorial, we are going to learn about the predefined macros in C++. Macros in C++ are the statements or expressions defined using #define. The given link will give you an insight of macros in C++, so do give it a read: C++ Pre-Processors.

C++ Predefined macros

In C++, we have some predefined macros. We don’t need to provide a definition to use these macros. Some of them have been listed here with examples.

  • __LINE__: This macro is useful in cases when we want to find an error along with its line number. It contains the line number of the statement it is used in. We mostly use this macro in debugging. We can redefine it using the #line directive. See the example code.
    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << __LINE__ << endl;
      return 0;
    }

    Output:

    6
  • __FILE__: This macro contains the name of the file within which we use it. This is mostly used in C++ programs for debugging along with __LINE__ macro. See the given code to understand.
    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << __FILE__ << endl;
      return 0;
    }

    Output:

    mac.cpp
  • __DATE__: __DATE__ macro in C++ contains the date of the program compilation i. e. the date at which it was compiled. The date is stored in the Mmm dd yyyy format as a string. Mmm is the month name returned by the function asctime().
    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << __DATE__ << endl;
      return 0;
    }

    Output:

    Feb 18 2020
  • __TIME__: This macro expands to a string that contains the time at which the corresponding file was compiled. The time format is “hh:mm:ss”. See the below code.
    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << __TIME__ << endl;
      return 0;
    }

    Output:

    07:03:03
  • __cplusplus: This macro is used to find the version that our C++ compiler supports. It expands to 199711L for C++98 and C++03, to 201103L for C++11, and to 201402L for C++14 standard. See the code for example.
    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << __cplusplus << endl;
      return 0;
    }

    Output:

    199711
  • __STDC__: This macro is used to check whether the compiler conforms to ISO standard C or not. If it does it expands to value 1. See the code.
    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << __STDC__ << endl;
      return 0;
    }

    Output:

    1

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *