Polyglot: Write Once, Compile Anywhere

No, that’s not a brand new programming language. Polyglot is a term for a source code that is syntactically correct in several languages. The program can be successfully compilable in those languages. Interestingly, the resulting executable file usually performs the same operation or output.

Polyglot is usually created only for fun. It is mainly consists of clever and unusual syntaxes, but that’s the art!

Now, take a look at an example of polyglot from wikipedia.

#define a /*
echo "?10Hello, world!\n";// 2> /dev/null > /dev/null \ ;
// 2> /dev/null; x=a;
$x=5; // 2> /dev/null \ ;
if (($x))
// 2> /dev/null; then
return 0;
// 2> /dev/null; fi
#define e ?>
#define b */
#include <stdio.h>
#define main() int main()
#define printf printf(
#define true )
#define function
function main()
printf "Hello, world!\n"true/* 2> /dev/null | grep -v true*/;
return 0;
#define c /*

Believe it or not, the above code is compilable in ANSI C, PHP, and bash!

There are plenty of polyglots in the internet. Try googling for it and you will discover many interesting examples. Even there is a polyglot which is syntactically correct in over 15 languages! It’s so cool, eh?

About Ashar Fuadi

Ashar Fuadi is a competitive programmer from University of Indonesia. He loves to code, especially for TopCoder SRM, Codeforces, and ICPC.
Follow Ashar on Google+ and Twitter.

Speak Your Mind