The output of this code is

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

I don't know how this is happening. Please explain.

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

int main()
{
        printf(str,34,str,34);

        return 1;
}

Recommended Answers

All 2 Replies

Any time you venture out into the "weeds" of undefined behavior, the results can be odd or just what you might expect.

The point is, why bother? It's an unproductive line of inquiry at best - a complete mockery of the standards of the C language, and your ability to see the wisdom of working within those standards, at worst.

Which parts are you confused about specifically? The %cs in the format string are used, so that the " characters (ASCII value 34) can be inserted without messing with backslashes. Other than that the main trick is that str is used both as the format string as well as the argument to %s, so that the format string can appear verbatim in the printed output without having to repeat it.

PS: To make this a proper quine you should add the include, the return type of main and the return statemetn to the format string. You'd also need to add additional %cs for the line breaks if you want those to be reproduced as well.

PPS: When the application exits successfully, it should return 0, not 1.

Any time you venture out into the "weeds" of undefined behavior, the results can be odd or just what you might expect.

Where and how does this code invoke undefined behavior? I don't see it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.