Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Nested Comments forbidden?

Why are nested comments forbidden in C++, Java inspite of the fact that nested comments are useful, neat, and elegant and can be used to comment out statements that have comments?

like image 941
Primal Pappachan Avatar asked Jun 03 '10 19:06

Primal Pappachan


People also ask

Why nested comments are not allowed in C?

C and C++ do it for ease of parsing. This way, when they hit a comment start of /*, the parser can trivially scan to the end. Otherwise, it would have to set up and maintain a stack, and then report errors if the comment tokens are unmatched.

Can a multi-line comment be nested?

Multi-line comments are visible to Scheme as a single whitespace. Multi-line comments may be nested: Every #| within the comment starts a new multi-line comment, which has to be terminated by a matching |# .

What does nested comment mean?

A nested comment is a comment inside another comment.


2 Answers

C and C++ do it for ease of parsing. This way, when they hit a comment start of /*, the parser can trivially scan to the end. Otherwise, it would have to set up and maintain a stack, and then report errors if the comment tokens are unmatched.

As to why Java does it, the answer is simple - Java's syntax was designed to emulate C and C++. If nested comments were allowed, it might trip up some C programmers, and many angry blog posts would be written!

like image 62
Clark Gaebel Avatar answered Sep 30 '22 19:09

Clark Gaebel


At least for C++ that's only partly true, there's no problem with:

/*
//
//
*/

However if you already got an /* comment in a section you want to comment out you might be able to do it by surrounding it with an #if 0 which I think many compilers optimize away. As in:

#if 0
/*

*/
#endif
like image 22
Hans Olsson Avatar answered Sep 30 '22 21:09

Hans Olsson