0

I could not understand how the below program code outputs that value.Please help me to understand.

#include<stdio.h>
char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
int main()
{
        printf(s,34,s,34);
        return 0;
}

output:

char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}
4
  • 5
    Do you understand how printf works? Commented Aug 16, 2011 at 16:55
  • 1
    Hint: this is not a macro function. Commented Aug 16, 2011 at 16:57
  • Sorry this is not a macro function. I was going through bunch of these questions and have given the heading wrongly. Commented Aug 16, 2011 at 16:59
  • Thanks for making me to understand about how the output got arrrived. Commented Aug 16, 2011 at 17:22

3 Answers 3

2

It isn't actually a macro in use here. It is just a simple call to printf. The first parameter to printf is the format string. In this case it is the value defined in the global variable s. The format characters %c%s%c are supplied by parameters 34,s,34". So the string is just printed in its entirety because of the %s format character. And the two 34 values are printed as double quote characters (via %c).

Sign up to request clarification or add additional context in comments.

Comments

1

Your printf statement is effectively equivalent to:

printf("char*s=%c%s%c;main(){printf(s,34,s,34);}", 34, s, 34);
               ^ ^ ^

I've marked the conversion specifiers with ^. These get replaced with, respectively:

  • " - the ASCII character corresponding to 34
  • the contents of *s
  • " - the ASCII character corresponding to 34

Comments

0

You are inserting as an argument your format string, so the output is correct. The %s is replaced with the actual format. PS: Where are macros?

1 Comment

Correct, I forgot to write it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.