For loop with printf as arguments

  • A+

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; } 




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).



:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: