Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better way to write comments in C?

In C we can make comments in two ways:

1>

/* this is one way */

2>

// this is 2nd way

What is the difference between the two?
Is one better than the other?

or

do both have same impact and no difference in compiling or processing at any platform?

Edit : Especially writing code for embedded

like image 425
Jeegar Patel Avatar asked Sep 07 '11 08:09

Jeegar Patel


2 Answers

Technically, only the first way is guaranteed to work on all compilers, present and past. In practice, all C compilers implemented since the mid-1980s or so implement both ways, so unless you will be writing for a legacy compiler, you can do whichever way works best for you or your organization.

like image 167
wallyk Avatar answered Oct 05 '22 01:10

wallyk


One (perhaps theoretical) reason not to use // comments is that they're not supported in C90. It's true that most, perhaps all, modern C compilers do support // comments, even if they don't support the rest of C99, but different compilers support different subsets of C99.

Any compiler that supports the C90 will reject (or at least warn about) // comments if you invoke it in a C90-conforming mode.

If you're fanatical about portability, and you want to ensure that your code will compile with any C compiler, then you should compile it in C90-conforming mode -- which means // comments will be rejected. You can enable extensions or partial (or even full) C99 conformance, but then you'll be enabling other C99 features as well -- and your compiler won't warn you about other C99-specific features that you might use accidentally.

And as Andrew Grimm's comment points out, some projects might have coding standards that require one form or the other.

For example, gcc supports both // comments and long long (as well as a number of other C99 features); enabling // comments in gcc disables diagnostics for long long.

But for most purposes, this probably isn't a good enough reason to avoid // comments. You can write reasonably portable code if you're aware of which features are C99-specific, which compilers support those features, and which compilers you care about supporting.

like image 20
Keith Thompson Avatar answered Oct 05 '22 00:10

Keith Thompson