1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Existence of universal C++/Python Polyglot

Discussão em 'Python' iniciado por Stack, Setembro 10, 2025.

  1. Stack

    Stack Membro Participativo

    Polyglot is a name given to programs that are valid in more than one language.

    For example,

    #include <stdio.h>
    #define do main()
    do {
    printf("Hello World!\n");
    }


    is valid in C and Perl.

    I am not a programmer, only a mathematician who was writing a few examples for the students. I was writing the the examples with both C++ and Python versions for their convenience, when I wondered of the posibility of having the two versions in the same file. I didn't know the existence of the term polyglot (refering to programs) or that they can be such a source of fun.

    My question is: Is it known a technique to have a universal polyglot for C++ and Python. By universal I mean that rather than being a single program, it is a template that allows to rewrite any (reasonably short) program in C++ and its version for Python into a polyglot that combines them.

    Maybe I should ask first for existence of C++/Python polyglots, because in my searches I didn't see a C++/Python polyglot.

    I posted it here because I wanted the polyglot for a slightly practical reason. I could post it in Programming Puzzles & Code Golf. If it should go there instead.

    For me it is hard to judge the existence or materialize a solution. I don't have much experience on these clever constructions.

    I tried enclosing the Python part between #if 0 and #endif, which would be comments in Python and tell C++ to ignore that part. For the C++-usable part I tried enclosing it into the docstring, which for most effects would be ignored by Python. But couldn't find a way to make the quotation marks acceptable for both Python and C++.

    #if 0
    print('Hi there')
    #endif
    #if 0
    """
    #endif
    #include<iostream>
    int main() {
    std::cout << "Hi there" << std::endl;
    return 0;
    }
    #if 0
    """
    #endif


    For C++, we got for """:


    warning: missing terminating " character
    ​

    Continue reading...

Compartilhe esta Página