When can I omit curly braces in C?

2020-02-10 14:49发布

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 statements before, such as

if (condition)
  return 5;

But this doesn't always seem to work for all statements, i.e. when declaring a method.

edit:

Are the rules for brace omission the same as in Java?

标签: c
9条回答
姐就是有狂的资本
2楼-- · 2020-02-10 15:06

You mainly need curly braces when you want to combine multiple statements or expressions into one, e.g.:

{
  x = 1;
  y = 2;
}

So if you put the above under if or else the whole thing in the braces will be executed as a whole, whereas if you omit the braces, only the first one (x = 1; in this case) will be used as part of if or else.

You also typically use them with switch():

switch (x)
{
case 1:
  // do smth
  break;
case 2:
  // do smth else
  break;
}

You typically need them with the do-while statement:

do
{
  printf("%d\n", x);
  x++;
} while (x < 10);

You need them with C89 compilers when you want to define and use a temporary variable in the middle of the code:

int main(void)
{
  puts("Hello World!");
  {
    int x;
    for (x = 0; x < 10; x++)
      printf("%d\n", x);
  }
  return 0;
}

You use them to begin and end the body of a function, a structure/union definition, an enumeration definition, initialization of a structure/union/array, e.g.:

void blah(void)
{
}

enum e
{
  e1 = 1,
  e2 = 2
};

struct s
{
  int foo;
  int bar;
} s = { 1, 2 };

int a[3] = { 1, 2, 3 };

You may omit them sometimes in initializations, e.g.:

char str2[] = { "abc" };
char str1[] = "abc";
查看更多
▲ chillily
3楼-- · 2020-02-10 15:06

Anytime there is a block with more than one line (counting lines as a single statement with a ; )

Examples:

for (i = 0; i < j; i++ ) 
   foo(i);

while (1) 
   foo();

if( bool )
   foo();

void cheese()
   printf("CHEESE");

Everything after the ; in the above lines does not count as 'inside' the block as if there were { }.

查看更多
混吃等死
4楼-- · 2020-02-10 15:08

If in doubt, use braces. They don't "cost" any extra [unless you absolutely use them incorrectly].

A fairly basic rule is "if you have more than one semicolon at the same indentation, you should have braces". It's not entirely that simple, but as a "one sentence with no ifs, buts or other complications" it will have to do.

And yes, Java being based on C-syntax has the same fundamental rules - there are possibly some weirdness where Java is different from C or C++, but that's unusual/strange things, not something you'd normally hit when writing typical code [I haven't done much java, so I can't say I've found any of them, but I'm pretty sure there are SOME differences - they are different languages, after all].

查看更多
登录 后发表回答