Wednesday 16 October 2013

How to implement Short Quines in C?


1) Quine Using Macros :

#define Z(x)t=#x;x
Z(main(){printf("#define Z(x)t=#x;x\nZ(%s)",t);})

2) Use a variable without declaring
b;main(a,s){printf(s="b;main(a,s){printf(s=%c%s%c,34,s,34,a,b);}",34,s,34,a,b);}

In the above quine, there is no need to declare s char *s


3) Initialize variables without assigning values explicitly
b;main(a,s){printf(s="b;main(a,s){printf(s=%c%s%c,34,s,34,a,b);}",34,s,34,a,b);}

In the above quine, a and b are integer variables initialized to 1 and 0 respectively.

4) Use ternary operators if possible
#define Z(x)t=#x;x
Z(main(i){for(;12%++i;);printf(i-12?"#define Z(x)t=#x;x\nZ(%s)":"YES",t);})

The above program acts as a quine if a number is composite else prints “Yes”.
Replace 12 by other numbers to check.

5) Use logical operators:

Example :
The code :

if(n%2==0)
n=n/2;
else
n=n*2;
printf(“%d\n”, n);

can be rewritten as :

printf("%d\n", n%2?n*2:n/2);

No comments:

Post a Comment