Loopz
Loopz

Reputation: 199

At which circumstances can I omit curly braces in C?

I'm reading the famous K&R book and get stucked by the example in 1.6.

#include <stdio.h>
/* count digits, white space, others */
main()
{
    int c, i, nwhite, nother;
    int ndigit[10];
    nwhite = nother = 0;

    for (i = 0; i < 10; ++i)
        ndigit[i] = 0;

    while ((c = getchar()) != EOF)
        if (c >= '0' && c <= '9')
            ++ndigit[c-'0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++nwhite;
        else
            ++nother;

    printf("digits =");

    for (i = 0; i < 10; ++i)
        printf(" %d", ndigit[i]);

    printf(", white space = %d, other = %d\n", nwhite, nother);
}

Here why can the while statement work without curly braces? I know that if there is only one statement in the block then they can be omitted. But it seems to me that if...else if...else is not a single statement. Can anyone explain that to me?

Upvotes: 4

Views: 132

Answers (2)

Josh123
Josh123

Reputation: 159

If Curly Braces are removed from an expression, the expression will only be executed for a single statement.

Upvotes: -4

ouah
ouah

Reputation: 145829

The syntax of the while statement is:

while ( expression ) statement

In C syntax a statement is either:

statement:
    labeled-statement
    compound-statement
    expression-statement
    selection-statement
    iteration-statement
    jump-statement

and a selection-statement is defined as:

selection-statement:
    if ( expression ) statement
    if ( expression ) statement else statement
    switch ( expression ) statement

So as you can see a if .. else if .. else is itself a statement.

You may also notice that a compound statement is itself a statement, so for example, this block:

{
    statement1;
    statement2;
}

is also a statement.

Upvotes: 7

Related Questions