Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple printf in the For-loop as part of the initialization, condition and update

Tags:

c

loops

printf

Could anyone explain to me why it prints 32 and the overall concept of how this works?

#include <stdio.h>

int main()
{
    int a=1;
    for (printf ("3"); printf ("2"); printf ("1"))

    return 0;
}
like image 581
synth Avatar asked Jan 25 '23 05:01

synth


1 Answers

Proper indentation would make it clearer:

#include <stdio.h>

int main()
{
    int a=1;
    for (printf ("3"); printf ("2"); printf ("1"))
        return 0;
}

So the following happens:

  • a is initialized to 1. I don't know why this variable exists, since it's never used.
  • for executes its initialization statement, printf("3");. This prints 3.
  • for evaluates its repetition condition, printf("2"). This prints 2 and returns the number of characters that were printed, which is 1.
  • Since the condition is truthy, it goes into the body of the loop.
  • The body executes return 0;. This returns from main(), thus ending the loop.

Since the loop ends, we never evaluates the update expression, printf("1"), so it never prints 1. And we get no repetition of anything.

like image 53
Barmar Avatar answered Feb 14 '23 11:02

Barmar