简体   繁体   中英

Comments in if statement without curly braces

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?)

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?

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.

是的,注释不会在编译中考虑,因此不会更改代码的语义。

是的,您可以根据需要添加注释。编译器仅忽略多行和单行注释

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM