Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
284 views
Welcome To Ask or Share your Answers For Others

1 Answer

The only places you can omit brackets are for the bodies of if-else, for, while, or do-while statements if the body consists of a single statement:

if (cond)
  do_something();

for (;;)
  do_something();

while(condition)
  do_something();

do 
  do_something();
while(condition);

However, note that each of the above examples counts as single statement according to the grammar; that means you can write something like

if (cond1)
  if (cond2)
    do_something();

This is perfectly legal; if (cond2) do_something(); reduces to a single statement. So, for that matter, does if (cond1) if (cond2) do_something();, so you could descend further into madness with something like

for (i=0; i < N; i++)
  if (cond1)
    if (cond2)
      while (cond3)
        for (j=0; j < M; j++)
          do_something(); 

Don't do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...