__FILE__ and __LINE__ in C: What They Are and How to Use Them
__FILE__ and __LINE__ are special macros in C that give the current source file name and line number respectively. They help track where code is during compilation, useful for debugging and logging.How It Works
Imagine you are reading a book and want to note exactly which page and line you are on. In C programming, __FILE__ and __LINE__ do something similar for your code. __FILE__ holds the name of the current source file as a string, and __LINE__ holds the current line number as an integer.
These macros are replaced by the compiler before the program runs. So, wherever you put them in your code, they automatically fill in the file name and line number at that spot. This helps you know exactly where something happened in your code, like a message or an error.
Example
This example shows how __FILE__ and __LINE__ print the current file name and line number.
#include <stdio.h> int main() { printf("This is file: %s\n", __FILE__); printf("This is line: %d\n", __LINE__); return 0; }
When to Use
Use __FILE__ and __LINE__ when you want to know exactly where in your code something happens. This is very helpful for debugging errors or logging events.
For example, if your program crashes or behaves unexpectedly, printing the file and line number can tell you the exact spot to check. They are also useful in writing error messages or assertions that help find bugs faster.
Key Points
__FILE__is a string with the current source file name.__LINE__is an integer with the current line number.- Both are replaced by the compiler before running the program.
- They help with debugging and logging by showing where code runs.
Key Takeaways
__FILE__ and __LINE__ provide the current file name and line number in C code.