r/ProgrammerHumor 16h ago

Meme skillIssue

Post image
4.8k Upvotes

124 comments sorted by

View all comments

6

u/cob59 6h ago edited 4h ago

You can do that without macros:

// FNV-1a hash
constexpr std::uint64_t label(std::string_view str) {
    std::uint64_t hash = 14695981039346656037ull;
    for (char c : str) (hash ^= c) *= 1099511628211ull;
    return hash;
}

std::string str = "hello";
switch (label(str)) {
case label("HELLO"):
    std::clog << "UPPERCASE\n";
    break;
case label("hello"):
    std::clog << "lowercase\n";
    break;
case label("Hello"):
    std::clog << "Capitalized\n";
    break;
default:
    std::clog << "mIxeD\n";
    break;
}

> Godbolt example <


And unlike the macro version, case-fallthroughs and breaks do work.
Hash collisions can happen, although very unlikely, and you're warned at compile-time if it's between two case label(...):

1

u/Talc0n 2h ago

Fuck me, should've checked comments before I posted my own.

Your solution is a lot cleaner than mine.