Wednesday, January 20, 2010

Episode Fourteen: Proper Closure

It's polite to include proper closing when writing letters or emails. C++ is actually stricter, and enforces proper file closing in standard compliant code. Unfortunately most -if not all- current compilers would humour nonstandard impolite code; some won't even issue a warning. As a result, portable yet nonstandard code gets away with it.

From the standard (n3000), 2.2.3:
A source file shall not end in a partial preprocessing token or in a partial comment.
A partial preprocessing token would arise for instance from an include directive that is missing the closing " or >. Those are obvious errors, and luckily compilers think so as well since they wouldn't know how to recover from it anyway. Unclosed /*multiline comments*/ would issue errors as well. However, single line comments are a different story. Single line comments span from a // token until the next (unescaped) new-line character. This means that code like the following is not legal C++:
#endif // SCOPE_GUARD_HPP [Note: no new-line here][EOF]
There is yet another reason why such code would be illegal, even without its comment. From the standard (n3000), 2.2.2:
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, the behavior is undeļ¬ned.
In simple words, standard C++ source code files end in an unescaped new-line character; with the single exception of empty files. Anything else is nonstandard, even when its portable across (probably) any compiler known to man.

No comments:

Post a Comment