Igwe Kalu
Igwe Kalu

Reputation: 14888

Passing printf() as an argument to itself: printf("%",printf("%s", "something something"));

This is like a bit of a puzzle... I've just come back to C again with the intention of mastering it this time. So I have been reading The C Programming Language, and I came by this statement:

Among others, printf also recognizes ... %% for itself.

Something I didn't know earlier. So I started to play with this feature by writing this small piece of code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {

    int number = 300;
    printf("%\n\n%12d\n\n\n\n\n", printf("%\n\n\n\n\n\n", printf("%s", "foooo!")), number);

    return (EXIT_SUCCESS);
}

And here's the output: Output screenshot

I would expect 300 in the output. Where does the 2 come from - does anyone know?

EDIT

I realise this was totally a mistake due to my misunderstanding of the text I cited above. Thanks one and all for helping me realise that.

Upvotes: 1

Views: 490

Answers (2)

NPE
NPE

Reputation: 500933

You are not passing valid combinations of arguments to two out of three printf() calls. This results in undefined behaviour.

Among others, printf also recognizes ... %% for itself.

What this means is that %% in the format specifier results in a % being written to the output.

It has nothing to do with passing the return value of printf() (which is the number of characters written) to another printf() call. And, besides, your code doesn't even contain %%.

Upvotes: 10

user1508519
user1508519

Reputation:

A % followed by another % character will write a single % to the stream.

It sees % followed by a \n which is not a valid format specifier. Your format string also does not match your arguments. The return value of printf is the number of characters successfully written. Therefore it is a number. If your format string does not match the number of arguments passed to printf, it is undefined behavior.

printf("%12d    %d ",          printf("%d",          printf("%s", "foooo!")), number);
        number  ret of printf--^       ret of printf-^

Upvotes: 2

Related Questions