What is Predefined Macro in C: Simple Explanation and Examples
predefined macro is a special name that the compiler automatically defines before your program runs. These macros provide useful information like the current file name, line number, or compilation date, and you can use them to make your code more informative and easier to debug.How It Works
Think of predefined macros as built-in labels that the C compiler attaches to your code automatically. They act like sticky notes that tell you details about your program's environment, such as where the code is located or when it was compiled.
When you write your program, you don't have to define these macros yourself. The compiler fills them in with the right values during compilation. For example, __FILE__ holds the name of the current source file, and __LINE__ holds the line number in that file. This helps you track where things happen in your code, especially when debugging.
Example
This example shows how to use some common predefined macros to print the file name, line number, and compilation date.
#include <stdio.h> int main() { printf("File: %s\n", __FILE__); printf("Line: %d\n", __LINE__); printf("Compiled on: %s at %s\n", __DATE__, __TIME__); return 0; }
When to Use
Predefined macros are very useful when you want to add helpful information to your program without extra effort. For example, you can use them to print error messages that include the exact file and line where the error happened. This makes debugging faster and easier.
They are also handy for logging, version tracking, or conditional compilation depending on the date or time. In large projects, these macros help keep track of code changes and where specific code runs.
Key Points
- Predefined macros are automatically set by the compiler.
- They provide information like file name, line number, date, and time.
- They help with debugging and logging.
- You do not need to define them yourself.
- Common macros include
__FILE__,__LINE__,__DATE__, and__TIME__.