Polyglot programs

Monday 2 September 2002This is 21 years old. Be careful.

While looking for information for my entry on obfuscated code, I came across polyglot, a program in seven different programming languages at once. That is, one program text can be interpreted as being written in any of seven different languages, and produces the same result in each. This is indeed an impressive achievement, though mainly in figuring out how to exploit the differences and details of comment syntax in the different languages.

I have a similar program, written sometime in the early ‘90’s, I think. It is only for two languages, C and PostScript:

/* % Dual program: C or PostScript!
   % Ned Batchelder
   ( */
# include <stdio.h>
# include <string.h>
/* ) */char count , def = 0 ;
/* */main()
    char * /* */Courier = " findfont " + 36 , scalefont = 0 ;
    char * setfont = "(Hello, world!)" + 0 * 100 + 0 * 100 - 0 ;

    printf("%.*s\n", strlen(setfont)-2, setfont+1);
    return ;

char * exec ;

Although mine is only for two languages rather than seven, I like the way it maps a little better: the string “Hello, world!” only appears once, and is interpreted as a string in both languages, and the “printf” token is the one that puts the string out in both languages.

Other polyglot programs:


I've worked with two of the three authors of Polyglot (Peter and Kevin.) They are even smarter than you would imagine by reading that code :)

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.