Maths Maniac
Maths Maniac

Reputation: 83

Why the Semicolon is not emptying the loop body?

The semicolon at the end of the for loop is suppose to empty the body and create a null loop. But why this is printing 6?

void main()
{
    int i;
    for(i=1;i<=5;i++);
    {
        printf("%d\n",i);
    }
}

Upvotes: 0

Views: 126

Answers (6)

it is quite simple:

for(i=1;i<=5;i++); will be executed 5 times, from 1 to 5 then i=6 ends the for loop and then a new "scoped" statement is executed:

printf("%d\n",i);

therefore prints 6

Upvotes: 1

pmg
pmg

Reputation: 108978

Try this for fun

#include <stdio.h>

int main(void)
{
    int i;
    for (i = 1; i <= 5; i++) /* void */;

    /* floating block one */
    {
        int i = 42; /* new i, hides old i */
        printf("%d\n",i);
    }

    /* floating block two */
    {
        printf("%d\n",i);
    }
}

Upvotes: 1

pastaleg
pastaleg

Reputation: 1838

Because you declare the int outside the null loop, the value is saved outside the increment loop.

Read more about it here

The extra brackets do not do anything here because the semicolon exits the loop.

Read more about brackets here.

Upvotes: 1

syntagma
syntagma

Reputation: 24344

The for loop for(i=1;i<=5;i++); will run exactly 5 times, incrementing i from 1 to 6 (even though the for loop body is a no-op). Thus, in here:

{
    printf("%d\n",i);
}

the program will print the current value of i, that is 6.

Upvotes: 1

Kriegel
Kriegel

Reputation: 433

The loop body is empty, otherwise it would print 1, 2, 3, 4, 5. But the loop head runs nethertheless and in each iteration it increases i. When it reaches 6 which is not <=5 the loop ends. Printing i after the loop prints i as 6. Incrementing i is a side effect of the loop.

Upvotes: 11

Ed Heal
Ed Heal

Reputation: 60017

It is.at the end of the loop i will be 6 and the printf does this.

Upvotes: 1

Related Questions