Explain C code snippet: preprocessor + printf =?
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(scan开发者_开发问答f, scanf);
}
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 ...
???
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.
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.
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.
to understand this code,run the following statements one by one:-
printf("%s is a string","StRiNG");
printf("%s %s is a string","StRiNG");
printf("%s is a string","StRiNG","Hey");
精彩评论