Effect of semicolon after 'for' loop

前端 未结 5 1528
谎友^
谎友^ 2020-11-27 07:36

Say I want to print a message in C five times using a for loop. Why is it that if I add a semicolon after for loop like this:

for (i=0;i<5;i+         


        
5条回答
  •  心在旅途
    2020-11-27 08:04

    Semicolon is a legitimate statement called null statement * that means "do nothing". Since the for loop executes a single operation (which could be a block enclosed in {}) semicolon is treated as the body of the loop, resulting in the behavior that you observed.

    The following code

     for (i=0;i<5;i++);
     {
         printf("hello\n");
     }
    

    is interpreted as follows:

    • Repeat five times for (i=0;i<5;i++)
    • ... do nothing (semicolon)
    • Open a new scope for local variables {
    • ... Print "hello"
    • Close the scope }

    As you can see, the operation that gets repeated is ;, not the printf.


    * See K&R, section 1.5.2

提交回复
热议问题