I was discussing C programming styles with some students and when we were talking about comments, one of them noted that he doesn't use C++ comments in C code because they are a bad idea. Turns out that it was based on personal experience with multi-line C++ comments, but it's not the first time I've heard that claim. So, is //
considered harmful and if so, then why?
views:
276answers:
8If you use C++ comments in C, chances are that some C compilers won't accept your code. I would consider this harmful.
Saying something is a bad idea without any kind of justification seems like a bad idea to me.
The only problem I can see //
causing is when you're using older compilers that don't support that kind of comment.
It depends what version of C you are using. C 99 allows // as a comment, whereas C 89 doesn't.
If you want to be as backward compatible as possible, don't use them. But, I think this is an extreme fringe case. I'm willing to bet almost everyone uses C 99.
Edit: Any recent version of GCC is uses most of C99. You can find more info in Wikipedia.
C++-style comments were added to C with the (not yet widely supported) C99 standard. While the standard itself isn't widely supported in full, some parts of it (like the C++ style comments), are supported in almost every compiler by now. Considering that they were added, it means that there's a need for them, so it's easy to figure out that it wouldn't be considered bad style -- especially if you set yourself guidelines on where to use which.
Only reason not to use them is if you want to write a well-formed C89 compilant program.
"//" is supported in C99, but in C89 (which is the by far most supported dialect) it's not supported.
One common reason why people use //
instead of /* */
is that you can "nest" the former and not the latter, and so you can comment out code that has comments in it. But you should really be using #if 0
for commenting out code in C anyways.
C++ comments are not allowed as per the MISRA-C 2004 standard. Certain industries (automotive, specifically) prize MISRA compliant code and therefore, C++ comments are not allowed. I believe the same goes for other static code checking tools such as LDRA, etc...
This doesn't make them inherently bad, but it does mean that if you get into certain industries and want to work professionally, you will be actively discouraged from using C++ style comments.
This really shouldn't be of any concern these days, unless you're maintaining code for written specifically to compile with ancient compilers and the likes.