2

I am learning chapter 2: types, operators and expressions of "The C programming language Edition 2", and encounter such a snippet of code:

/* atoi: convert s to integer */
int atoi(char s[]) {
    int i, n;

    n = 0;
    for (i=0; s[i]>='0' && s[i] <= '9'; ++i)
        n = 10 * n + (s[i] - '0');

}

What's puzzle me is that n = 10 * n + (s[i] - '0'); is not enbraced within {}, I assume it should be

/* atoi: convert s to integer */
int atoi(char s[]) {
    int i, n;

    n = 0;
    for (i=0; s[i]>='0' && s[i] <= '9'; ++i) {
        n = 10 * n + (s[i] - '0');
    }

}

What's the problem with my assumption?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • `{}` are optional if the loop body is a single line – awesoon Oct 13 '18 at 08:58
  • 1
    And right to the SO. Learn more a bit. – purec Oct 13 '18 at 08:58
  • 4
    @soon Not single line, a single *statement*. – Some programmer dude Oct 13 '18 at 09:01
  • Following the `for` statement comes 1 statement or a block of statements. A block of statements is enclosed in `{` and `}` and counts as 1 statement. An empty statement ("do nothing") is denoted by `;` and is also considered 1 statement. – Paul Ogilvie Oct 13 '18 at 09:02
  • Though they are optional I suggest to always use braces in `for` loop bodies. This prevents silly bugs when you later want to add another statement, not noticing the missing braces. If I see a `for` loop without braces in code of peer devs, I immediately ask myself if they have such a bug. – zett42 Oct 13 '18 at 09:04

2 Answers2

4

The syntax for the for loop can be read in 6.8.5 Iteration statements:

for ( expression_opt ; expression_opt ; expression_opt ) statement
for ( declaration expression_opt ; expression_opt ) statement

In turn, a statement is (6.8 Statements and blocks):

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

The compound-statement is the one you are using when you write

for (i=0; s[i]>='0' && s[i] <= '9'; ++i) {
    n = 10 * n + (s[i] - '0');
}

However, when you write:

for (i=0; s[i]>='0' && s[i] <= '9'; ++i)
    n = 10 * n + (s[i] - '0');

You are using an expression-statement.

Acorn
  • 24,970
  • 5
  • 40
  • 69
2

If you have just one statement in a loop the braces are optional. If you have more than one statement you must put braces.

mariusd96
  • 95
  • 5
  • 6
    If you could reference the standard here, this could be considered an answer. Otherwise it is no more than a comment. – Paul Ogilvie Oct 13 '18 at 09:04