I want the dry run of the code for the first 3 iterations to understand. THe output of the code is : abcdbcdbcdbcdbc........(infinte times)
I know how for loop works and put char also.I did not dry run as i was not understand will the third argument in the for loop will increment or not.
#include <stdio.h>
int main()
{
for (putchar('a');putchar('b');putchar('d'))
putchar('c');
return 0;
}
putchar
always returns the char that you put. So for instance, putchar('a')
returns 'a'
. With that in mind, let's have a look at how the for
loop works:
for ( init_clause ; cond_expression ; iteration_expression ) loop_statement
The init_clause
is putchar('a')
. This prints a
once, because the init_clause
is evaluated once at the beginning of the for
loop.
The cond_expression
is putchar('b')
. This is checked every run through the loop, which is why it always prints b
. And as it returns 'b'
every time, the loop never stops. The loop would only stop if the cond_expression
returned 0
or the loop is exited otherwise, for instance through break
.
The iteration_expression
is putchar('d')
, hence d
is printed every time. The loop_statement
is putchar('c')
, printing c
.
The result is printing a
once, followed by an infinite amount of bcd
. The reason why you get them in this order is because in every run throught the loop, it first checks the cond_expression
, executes the loop_statement
and then the iteration_expression
.