Search code examples
creturnprintfreturn-value

Why printf("test"); does not give any error?


If int x=printf("test"); executes safely, without error in because printf returns an int value (the length of data it has printed.) But what about if we are not storing that integer value:

printf("text"); 

Why don't we get an error from this?


Solution

  • Many functions in C return something. Whether the programmer decides to do anything with that value is up to them - and often ignoring the return code leads to bugs... But in the case of printf(), the return value is seldom useful. It is provided for to allow the following code:

    int width;
    
    width = printf("%d", value); // Find out how wide it was
    while (width++<15) printf(" ");
    width = printf("%s", name);
    while (width++<30) printf(" ");
    

    I'm not saying that's good code (there are other ways to do this too!), but it describes why a function could return a value that isn't used very often.

    If the programmer does decide to ignore the return value, there isn't a compiler error - the value is merely forgotten. It's a bit like buying something, getting the receipt, and dropping it on the floor - ignore the returned value.

    The latest compilers can be instructed to flag code where returned values are ignored. But even these compilers can be taught which functions' returns are significant and which aren't. printf() would be in the second category.