What does printf() return?

Upon a successful return, the printf() function returns the number of characters printed (not including the trailing '\0' used to end output to Strings). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\0') which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. If an output error is encountered, a negative value is returned. There is a very funny yet interesting interview question around this.

Consider the following code snippet: 

void main() {
  if (X) {
    printf("Hello");
  } else {
    printf("World");
  }
}

What function should X be replaced with inorder to get the output as "Hello World"

And the answer is ...

#include <stdio.h>

int main() {
  if (!printf("Hello")) {
    printf("Hello");
  } else {
    printf(" World");
  }
}

 

C Programming Questions