#include <stdio.h>
int main()
{
        int i=43;
        printf("%d\n",printf("%d",printf("%d",i)));
        return 0;
}

Yes it is valid

because printf return number of written characters. but if printf did not return a value, this program would be valid.

this case is alittle hard to explain. %d in formatting string will look for suitable parameter, but if can not find it will put a dummy data availbale in memory so this program will work or it is valid.

but if printf did not return a value, this program would be valid.

If printf didn't return a value, it would return void. There aren't any values of void type, so something like this shouldn't ever compile. That means it's not valid.

#include <stdio.h>

void dummy( void ) { }

int main( void ) {
  printf( "%d\n", dummy() );

  return 0;
}

%d in formatting string will look for suitable parameter, but if can not find it will put a dummy data availbale in memory so this program will work or it is valid.

I thought that if there aren't enough arguments or if the arguments are a type that don't match the formatting string, the behavior of printf is undefined. I think that's how it works, but I'm not a guru. Can you show me where the standard document supports your explanation?

If printf didn't return a value, it would return void. There aren't any values of void type, so something like this shouldn't ever compile. That means it's not valid.

printf() always returns an int. Not a void type. If an error happens it will return a negative integer for EOF.

printf() always returns an int. Not a void type.

Yeah, I know. You should read my post again, and the post above it, more slowly this time. ;)

Yes, if you don't give printf() the correct arguments then its behavior is undefined. But most likely it will assum the stack contains the correct arguments and use whatever is there. That's why a lot of people get core dumps or access violations then they have "%s" in the format string but fail to pass a valid pointer to a character array.

As I mentioned in another thread, some compilers will validate the parameters to printf() and issue warnings is they are not correct. I wish all compilers did that :)

This article has been dead for over six months. Start a new discussion instead.