When can I omit curly braces in C?
c
Solution
The only places you can omit brackets are for the bodies of `if-else`, `for`, `while`, `do-while`, or `switch` 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.
Problem
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. Are the rules for brace omission the same as in Java?