When can I omit curly braces in C?

后端 未结 9 1947
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 09:14

I\'m almost certain this has been asked before, but I can\'t find it being answered anywhere.

When can I omit curly braces in C? I\'ve seen brace-less return

9条回答
  •  臣服心动
    2020-11-29 10:02

    You can omit them when there's a single statement you're executing:

    for(...)
     printf("brackets can be omited here");
    
    if(...)
     printf("brackets can be omited here");
    else
     printf("brackets can be omited here too");
    

    etc.. You can always add them in, it never hurts and help to clarify the scope, but you're pretty safe. The only "catch" I can think of is if you attempt to make a declaration in that scope (which is useless by the way):

    if(...)
      int a = 5;
    

    This will cause an error, but that's because you can perform a single statement without curly brackets, not a declaration. Important distinction.

    Technically speaking, you can even do more than one operation without brackets if they're concatenated with the , operator... not that I advice doing it, just worthy of note:

    if(...)
        value++, printf("updated value with brackets");
    

    And to your edit, you can see in the java specification that the rules are the same. I linked specifically to the if section, but you can see after the if it's expected a statement, thus you can skip the curly brackets.

提交回复
热议问题