For loop with printf as arguments

691 Views Asked by At

I can't understand why the following code outputs 10. What I understand is that !printf("0") means !0, which is TRUE. So why doesn't the code print "Sachin"

#include <stdio.h>

int main() {
    for (printf("1"); !printf("0"); printf("2"))
        printf("Sachin");
    return 0;
}

Output

10
3

There are 3 best solutions below

4
Jean-François Fabre On

let's analyze this side-effect loop statement:

for(printf("1"); !printf("0"); printf("2"))
  • The first statement is executed, always (init condition), yieiding 1
  • Then the condition is tested: !printf("0") prints 0, then since printf returns 1 because it just prints 1 character, the negation returns 0 and the loop is never entered because the condition is false right from the start. So neither 2 or Sachin are printed.

Of course, this code isn't practical, almost unreadable. So don't ever do things like this (puts("10"); is a good alternative for instance).

more on the return value of printf (that is often ignored):

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

(from https://linux.die.net/man/3/printf)

2
Malorke On

If you look at the man printf reference on google, you'll see that this function returns the number of written bytes.

Here your condition is !printf("0"), in other words : "as long as the return of printf is not existing (or equal 0), do something. But you print the character '0' so printf actually return 1 so your condition is false.

Now WHY it prints 10 :

  • The first printf("1") prints 1.
  • Your condition is tested at least once, so the second printf("0") occurs one time (it prints 0)
1
Milan Shah On
printf("1")

prints 1 and it return number of characters which is 1

printf("0")

prints 0 and it return number of characters which is 1

!1 means !(true) = false so execution will stop and you will see 10 as output.