Predefined Macros

Predefined macros are built-in macros provided by the C++ preprocessor. They convey information about the code, such as the current line number, source file name, and compilation date. These macros are automatically defined by the compiler and can be useful for debugging and logging purposes.

The following are some commonly used predefined macros in C++:

  1. __LINE__: This macro expands to the current line number in the source code.
  2. __FILE__: This macro expands to the name of the current source file.
  3. __DATE__: This macro expands to a string that represents the date of compilation.
  4. __TIME__: This macro expands to a string that represents the time of compilation.

Example

In this example, __LINE__ is replaced with the current line number, __FILE__ with the source file name and __DATE__ with the compilation date. These can be handy for debugging and logging.

C++




// C++ program to illustrate the predefined macros
#include <iostream>
using namespace std;
  
int main()
{
  
    // Display the current line number and the source file
    // name
    cout << "This is line " << __LINE__ << " in file "
         << __FILE__ << "\n";
  
    // Display the compilation date
    cout << "Compiled on " << __DATE__;
  
    return 0;
}


Output

This is line 10 in file ./Solution.cpp
Compiled on Nov  7 2023

Macros In C++

C++ is a powerful and versatile programming language that offers many features to enhance code flexibility and maintainability. One such feature is macros, which are preprocessor directives used for code generation and substitution. Macros are an essential part of C++ programming and play a crucial role in simplifying code, making it more readable and efficient. In this article, we will learn about the macros in C++.

Similar Reads

What are Macros?

In C++, a macro is part of code that is expanded to its value. Macros are defined using the #define directive. They provide a way to create symbolic constants and code snippets that can be reused throughout a program. Macros are processed by the C++ preprocessor, which runs before the actual compilation. During preprocessing, macros are replaced with their corresponding values, making it an effective tool for code generation and simplification....

Syntax

The syntax for defining a macro in C++ is as follows:...

Example of Macro

Let’s explore a simple example of a macro in C++. Suppose we want to create a macro to calculate the square of a number. Here’s how we can define and use a macro:...

Types of Macros in C++

...

Predefined Macros

Macros can be classified into four types in C++:...

Advantages of Macros

...

Disadvantages of Macros

...

Conclusion

...

Contact Us