views:

151

answers:

3

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?

+3  A: 

Conformance/compatibility with C.

ergosys
Didn't C only originally use the // comment symbol? Also, why would Java need to conform to the C standard?
tloach
@tloach: `//` does not exist in C before C99.
KennyTM
C originally used only /* */, and Java was intentionally patterned after C (and C++) to make it more familiar to existing programmers. Conform is probably too strong of a word here, but I'm not sure what would be better.
ergosys
@tloach - no. Originally C only had /* */ comments - which is why they are called C style comments. Most early C compilers also allowed them to be nested and many - gcc for example - still do for backward compatibility.
Dipstick
Ok, I had my comment styles mixed up apparently :) Thanks for the clarification.
tloach
+3  A: 

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
ho1
ALL compilers optimize that away, in the same way they "optimize" away multiple includes when header guards are used, as it's part of the preprocessing step.
Clark Gaebel
Compilers will not see this block, the *preprocessor* will have removed it before a compiler will lay its eyes on the code :).
Pieter
@wowus: Yes, you're right of course. I was thinking of `if(0)` which I think is compiler dependent.
ho1
+3  A: 

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++, to trick people into thinking it was just as fast (in the beginning, Java was purely interpreted, so this trick WAS necessary to get traction). If nested comments were allowed, it might trip up some C programmers, and many angry blog posts would be written!

Clark Gaebel