Longest C++ Variable Declaration
(478 words) Sat, Oct 26, 2019Here’s a challenge: what’s the longest variable declaration you can come up with?
That’s not useful in any way. Quite the opposite - the result is something you’d never want to see in your codebase. But it’s an interesting mental challenge, or at least so I think.
Ground rules:
Each keyword used gets you 1 point, repetitions allowed;
Must be global variable;
Must be valid C++17;
Must not declare new structs / classes / unions / functions / methods;
Variable must be initialized with empty braces, i.e
{}
;No comments of any type are allowed, nor usage of preprocessor;
Each ‘trick’ may only be used once.
Take a moment to think about it! Maybe you’ll come up with ideas I haven’t.
My Solution
Here’s roughly how my solution evolved:
// Most basic declaration - 1 point.
int a{};
// Some types are longer than others - 4 points
unsigned long long int a{};
// Adding constness - 6 points.
constexpr const unsigned long long int a{};
// With pointers you can add an additional const - 7 points.
constexpr const unsigned long long int* const a{};
// static - 8 points
static constexpr const unsigned long long int* const a{};
// Can you use thread_local with static? Apparently! - 9 points.
static thread_local constexpr const unsigned long long int* const a{};
// How 'bout static thread_local inline? Seems to work... - 10 points.
static thread_local inline constexpr const unsigned long long int* const a{};
// Here's a feature rarely used - volatile! - 11 points.
// (volatile constexpr - such a weird statement...)
static thread_local inline constexpr volatile const unsigned long long int* const a{};
Cheating, aka Stack Overflow
At this point, curious if I’m the only very bored C++ developer who came up with this challenge I decided to Google it.
I found this Stack Overflow thread with some interesting ideas. Someone came up with an easy way to get infinite points:
int const* const* const* const* const* const* const* const* /* ... */ a{};
This is the reason I added that last rule. It’s not well formulated I guess, but you get the spirit.
Additional idea is to use decltype
with typeid
:
// Adding decltype with typeid buys us additional 4 points, with a total of 15 points.
static thread_local inline constexpr volatile const decltype(typeid(const volatile unsigned long long int).name())* const a{};
And the last idea I read was to geniusly use alignas
with sizeof
, although I
personally prefer to use alignof
instead:
// Adding alignas with alignof / sizeof gets us to 25 points!
alignas(alignof(decltype(typeid(const volatile unsigned long long int)))) static thread_local inline constexpr volatile const decltype(typeid(const volatile unsigned long long int).name())* const a{};
This is as far as I got. I’m certain there are many more tricks I hadn’t thought of, or unaware of. Do you have any? Let me know in a comment!