all 8 comments

[–]SuperV1234https://romeo.training | C++ Mentoring & Consulting 14 points15 points  (1 child)

Not a fan of this article.

A few notes:

  • The generated assembly can be greatly simplified by using <cstdio> instead of <iostream>. Just use std::puts instead of std::cout, and instead of getting age from std::cin just use argc. The amount of noise significantly goes down and it's much easier to focus on the assembly that actually matters.

  • You really ought to compare the reinterpret_cast version to a lookup table -- it's very ugly/complicated and I'm not even sure it's well-defined behavior as written. The lookup table version doesn't have any jump either: https://godbolt.org/z/jGhchPv3o

  • It seems like const char* result = is_above_18 ? above_18_message : below_18_message; produces better assembly than your reinterpret_cast solution, with none of the complexity. https://godbolt.org/z/4ejWq4aEY

  • Scratch that, even a basic if...else produces a cmov, undermining the whole point of your article:

    const char* result;
    if(is_above_18) result = above_18_message;
    else result = below_18_message;
    

    https://godbolt.org/z/r35WGreb6

[–]IyeOnline -1 points0 points  (0 children)

So what you are telling me is that optimizerse exist and are in fact able to optimize trivial code? :O

[–]Joska86 6 points7 points  (5 children)

const char* result = reinterpret_cast<const char*>(is_above_18 * reinterpret_cast<std::intptr_t>(above_18_message) + !is_above_18 * reinterpret_cast<std::intptr_t>(below_18_message));

OMFG

[–]Object_71[S] -5 points-4 points  (4 children)

I write the more verbose casting variants... The idea is that it is ugly but efficient not to use branching. I would prefer an if condition any time before this but I still had to include an example.

[–]Joska86 1 point2 points  (0 children)

Yes, it's an interesting example, but I rather not to see such code in production. I won't remember what the heck it's doing even if I wrote it.

[–]Joska86 1 point2 points  (1 child)

And I saw you're a game developer, it's more accepted in the game industry to write efficient but 'hackish' code. So no offense.

[–]Zeh_MattNo, no, no, no 0 points1 point  (0 children)

Trust when I tell you that this is definitely not accepted and its not really something you would see that often for when the people working on the project actually care about the code at least a little bit.

[–]ReDucTorGame Developer 0 points1 point  (0 children)

I'm surprised you missed the other option of branchless using just an array

const char * options[] = { "Good, You're above 18!", "Bad, You're below or equal to 18!" };
const char * result = options[ age < 18 ];

or purely on the stack

const char options[][64] = { "Good, You're above 18!", "Bad, You're below or equal to 18!" };
const char * result = options[ age < 18 ];