Effect of semicolon after 'for' loop

前端 未结 5 1518
谎友^
谎友^ 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 07:50
    for (i=0;i<5;i++);
    

    is equivalent to

    for (i=0;i<5;i++){}
    
    0 讨论(0)
  • 2020-11-27 07:50

    This code below will print "Hello" 5 times..

        for(i=0;i<5,printf("Hello\n");i++);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 08:04

    Many compilers show a syntax error when you put a semicolon after a for loop but according to gcc compiler(Linux) or Dev-cpp you can put a semicolon after a for loop and it will not show you any errors.

    For example

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

    or

    for(int i=0;i<=5;i++) 
    {//blank body}
    

    From the above example it is clear if we put blank braces or semicolon after for loop that means we haven't entered any variable yet.

    Now come to your question.
    If you want to print hello five times, you have to write your program as

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

    I hope you understand
    cheers!!
    Rahul Vashisth

    0 讨论(0)
  • 2020-11-27 08:07

    The statement consisting of just the ; token is called the null statement and it does just... nothing.

    For example, this is valid:

    void foo(void)
    {
         ;
         ;
         ;
    } 
    

    It can be used everywhere a statement can be used, for example in:

    if (bla)
        ;
    else
        ;
    

    See the C Standard paragraph:

    (C99, 6.8.3p3) "A null statement (consisting of just a semicolon) performs no operations."

    0 讨论(0)
提交回复
热议问题