I do not understand the output of the following program:
#include <iostream>
#define FOO std::cout << __LINE__ << ' ' \
<< __LINE__ << '\n';
int main()
{
FOO
std::cout << __LINE__ << ' ' \
<< __LINE__ << '\n';
}
The first output is 7 and 7, indicating that the expansion of FOO is a single logical line, but the second output is 9 and 10, indicating two distinct logical lines. Why is there a difference?
Because
__LINE__expands to physical lines, not logical lines:While the lines ended by
\are concatenated in translation phase 2.The other only logical implementation would be to print 3 and 4 for the invocation of FOO, but that seems not very useful.
You can also look at this the following way:
__LINE__is not any different from any other macro. It’s just updated automatically by the compiler at the beginning of every line. So the code is kind of interpreted this way:This is not valid code, but it demonstrates how the things work. Apply the usual macro expansion rules and you’ll get the output you’ve got.