__LINE__ is a predefined macro. During preprocessing, which happens before the code is compiled, the preprocessor replaces it with the number of the source line where it appears. It works the same way in C and C++, and it gives you a simple way to record where in the source a piece of code sits.
A first example
#include <stdio.h>
int main(void) {
printf("This line is %d\n", __LINE__);
return 0;
}
The printf call is on line 4, so the program prints This line is 4. The C++ version works the same way:
#include <iostream>
int main() {
std::cout << "This line is " << __LINE__ << '\n';
}
What the value means
- The number is fixed when the code is compiled. It does not change while the program runs.
- Lines are counted from 1 in the file being compiled. Inside a header file,
__LINE__gives the line number in that header. __LINE__is an integer constant, not a variable. You cannot take its address or assign to it.
Logging with FILE and LINE
A common pattern pairs __LINE__ with __FILE__, which expands to the name of the source file as a string:
#include <stdio.h>
#define LOG(msg) printf("%s:%d: %s\n", __FILE__, __LINE__, msg)
int main(void) {
LOG("starting up");
return 0;
}
A macro is expanded where it is used, so the line number is the line of the LOG call, not the line where LOG is defined. If the file is named main.c, this program prints the file name and the line of the LOG call.
Changing the number with #line
The #line directive sets the line number for the line that follows it:
#include <stdio.h>
int main(void) {
#line 100
printf("%d\n", __LINE__); /* prints 100 */
return 0;
}
Tools that generate C code often use #line so that error messages point at the original source file instead of the generated one.
Things to avoid
- Do not define your own
__LINE__. Names that begin with two underscores are reserved for the implementation. - Do not use
__LINE__as a run-time counter. A loop or a function call never changes it, because its value comes from the source file.