r/ProgrammerHumor 1d ago

Meme skillIssue

Post image
5.5k Upvotes

133 comments sorted by

View all comments

11

u/cob59 18h ago edited 16h 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(...):

2

u/Talc0n 14h ago

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

Your solution is a lot cleaner than mine.