views:

87

answers:

4

The output for this code snippet is %s is a string is a string. Please explain.

#include <stdio.h>

#define scanf "%s is a string"

int main()
{
    printf(scanf, scanf);  
}
+5  A: 

What exactly do you want us to explain? Subsititute the macro and get

printf("%s is a string", "%s is a string");

The rest is the expected normal everyday behavior of printf.

P.S. #define scanf ...???

AndreyT
why is the output '%s is a string is a string' ?
Vish
@Vish: Because that's how `printf` works and that's what `printf` does. When you read the description of `printf` in your favorite C book or doc, was there something you couldn't understand?
AndreyT
@Vish: Think of it this way. The format string for the `printf()` call is `"%s is a string"`. There's a `"%s"` format so it takes the corresponding argument and substitutes it as a string. The first argument was the string `"%s is a string"`. Putting it all together, `"[%s is a string] is a string"` is printed (brackets added for emphasis).
Jeff M
+2  A: 

The preprocessor does a blind substitution to give:

printf("%s is a string","%s is a string");

The %s in the first argument is the format specifier for a string and is replaced with the 2nd argument. There is nothing special about the %s in the 2nd argument.

codaddict
+1  A: 

This is some rather bizarre code, but the output would be "%s is a string is a string" because scanf is expanded to "%s is a string" in both cases and then printf substitutes that in for the %s.

Dean Pucsek
A: 

printf("%s is a string","%s is a string");

I guess the confusion is what the printf will do with the second %s. To clear this, printf is not a recursive function. If you are printing a string and that string has any format-identifier it is not considered as format identifier. It is considered as plain string. So in this case the second "%s is a string" is just a plain string. %s in this string is not format-identifier.

If you had something like printf("%s %s is a string", "%s %s is a string"); Then yes you will get runtime error saying that printf is missing some argument.

Manoj R