Auf Kommentar antworten

Most concise C++ FizzBuzz

What is the most concise C++ FizzBuzz?

The following code appears initially to be a pretty good candidate:

#include <iostream>
#include <ostream>

using std::cout;

int main()
{
    for (int i=0;i++<100;)
        (!(i%3)&&cout<<"Fizz")|(!(i%5)&&cout<<"Buzz")||cout<<i,cout<<"\n";
}

But - alas! - this performs two modifications of std::cout in a single bitwise or expression (|). Because the operands to bitwise or (|) are evaluated in an unspecified order, this is officially undefined behaviour. See how codepad.org executes it.

So unfortunately we have to find a way to ensure that the first operand is executed before the second. That inevitably means evaluating the first operand separately, which unfortunately requires a variable.

However, all is not lost! Here is a way that takes us well into the realm of obfuscation:

#include <iostream>
#include <ostream>

using std::cout;

int main()
{
    for (int i=0,j;j=!(++i%3)&&cout<<"Fizz",i<101;j|(!(i%5)&&cout<<"Buzz")||cout<<i,cout<<"\n");
}

Antworten

  • Internet- und E-Mail-Adressen werden automatisch umgewandelt.
  • Zulässige HTML-Tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Zeilen und Absätze werden automatisch erzeugt.

Weitere Informationen über Formatierungsoptionen

CAPTCHA
Diese Frage prüft, ob Sie ein Mensch sind und kein Bot, um Spam vorzubeugen.
Bild-CAPTCHA
Enter the characters shown in the image.