1

Let's say we have this C code snippet:

if (condition)
    x = a;
else
    x = b;

Is it allowed to insert comments like this, without changing the semantics of the code:

if (condition)
    /* blah blah blah */
    x = a;
else
    x = b;

(if there were curly braces, the answer would be obviously yes, but what about these cases of if statements without curly braces?)

VividD
  • 10,456
  • 6
  • 64
  • 111

4 Answers4

3

Comments have no effect on the code other than the fact that they help to understand and edit code later.

The code you have shown is valid.

If the if statement is followed by codes inside curly braces all the codes inside the brace will get executed if the condition for if is met. If there is no curly braces to group the code, the statement immediately after the if statement gets executed. If there is comments before this statement it will not effect the code as the comments will be removed when the code is compiled.

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
  • The expression "If the if statement..." sounds clintonesque ("It depends on what the meaning of the word is is.") - http://www.slate.com/articles/news_and_politics/chatterbox/1998/09/bill_clinton_and_the_meaning_of_is.html – VividD Oct 27 '17 at 19:26
2

Yes. Comments are simply ignored and can be put anywhere that whitespace is allowed.

But I strongly urge you not to write if statements without curly braces. See Why is it considered a bad practice to omit curly braces?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • @EugeneSh. Is a blank line allowed inside of multiline macros? – Barmar Oct 05 '17 at 16:23
  • A completely blank - no. It has to have `\\`. – Eugene Sh. Oct 05 '17 at 16:24
  • Right. The comment is replaced by whitespace, but the extra newline is still there, so it acts the same as putting whitespace in the macro. – Barmar Oct 05 '17 at 16:25
  • @Barmar I always follow the advice to use curly braces, however, in some projects, coding standards are enforced, and they may require not using curly braces for one line if... – VividD Oct 05 '17 at 16:28
  • 2
    @VividD Really? I have never seen such a code standards. They are clearly against every good coding practice I have heard about. – Eugene Sh. Oct 05 '17 at 16:32
  • @EugeneSh. I would refrain from mentioning the name of such project, but it is a significant one. – VividD Oct 05 '17 at 16:43
2

Yes, the comments are not considered in the compilation and, therefore, does not change the semantics of your code.

Lukingan
  • 84
  • 7
2

Yes you can add comments as u wish.Compiler simply ignores multi-line as well as single line comments comments