What's the reason for the "No newline at end of file" warning in some C++ compilers? What's good about having an empty line at the end of a source\header file?
It isn't referring to a blank line, it's whether the last line (which can have content in it) is terminated with a newline.
Most text editors will put a newline at the end of the last line of a file, so if the last line doesn't have one, there is a risk that the file has been truncated. However, there are valid reasons why you might not want the newline so it is only a warning, not an error.
The answer for the "obedient" is "because the Standard says the behavior of a program not ending in newline is undefined" (paraphrased).
The answer for the curious is here: http://gcc.gnu.org/ml/gcc/2001-07/msg01120.html.
#include will replace its line with the literal contents of the file. If the file does not end with a newline, the line containing the #include that pulled it in will merge with the next line.
Think of some of the problems that can occur if there is no newline. According to the ANSI standard the #include of a file at the beginning inserts the file exactly as it is to the front of the file and does not insert the new line after the "#include " after the contents of the file. So if you include a file with no newline at the end to the parser it will be viewed as if the last line of foo.h is on the same line as the first line of foo.cpp. What if the last line of foo.h was a comment without a new line? Now the first line of foo.cpp is commented out. These are just a couple of examples of the types of problems that can creep up.
C++ Standard [2.1.1.2] declares:
... If a source file that is not empty does not end in a new-line character, or ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, the behavior is undefined.
a missing new line at the end can really cause a lot trouble in c++.
here is a simple example of error:
use visual c++, create a class header -with no ";" at the end of file - include it in a cpp, define constructor first in this cpp.
it gives error like: "constructor cannot have a return value"
such a silly error takes your days to solve. problem is that, you've forgotten to enter ";" at the end of header.
gcc solves this compilation problem by forcing you to enter a new line to each file. So that there is no problem when it is included somewhere.