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 acheivement, 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
   %
{pop}/,{}/={}/"{}/+{}/;{pop}/-{moveto}/printf{show}/return{showpage}9{def}repeat
   ( */
# 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:

tagged: programming languages» 1 reaction

Comments

[gravatar]
Alan Green 12:09 AM on 21 Jun 2004

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:

name
email
Ignore this:
not displayed and no spam.
Leave this empty:
www
not searched.
 
Name and either email or www are required.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.