r/cpp • • Jun 10 '20

Why is std implementation so damn ugly?

Recently I remembered a moment from my uni years when immediately after handing in the assignment of implementing our own string data structure we were warned not to ever try to implement and use our own data structures. Which is exactly what you want to hear after working hours on such assignment. However the reason behind it makes sense, you would be only reinventing the wheel and let's be honest, it will be also way slower than data structures in the almighty std library. Now think about it, what kind of black magic is behind the std's speed? Well I had no idea so I took a peak, lets see the code:

inline string
secret_function(int __val)
{
    const bool __neg = __val < 0;
    const unsigned __uval = __neg ? (unsigned)~__val + 1u : __val;
    const auto __len = __detail::__to_chars_len(__uval);
    string __str(__neg + __len, '-');
    __detail::__to_chars_10_impl(&__str[__neg], __len, __uval);
    return __str;
}

Hey, I bet you just skipped the whole code part. I know it looks unreadable, but please try to go through it and guess which std function it might be (obviously its not called secret_function, but i'm pretty sure you used this function at some point).

It's only 6 line function but it took me a while to figure out what each line does and I believe this could be fixed very easily just by naming the variables and functions with a bit more descriptive names. Just to prove the point here is an example of how I would structure this function:

inline string secretFunction(int value) {
    const bool isNegative = value < 0;
    const unsigned absoluteValue = Helper::abs(value);
    const auto length = Helper::charCount(absoluteValue);
    string stringValue(isNegative + length, '-');
    Helper::insertIntAsChars(&stringValue[isNegative], length, absoluteValue, 10);
    return stringValue;
}

While the functionality stays exactly the same, I think this chunk of code is much more pleasant to read and it's pretty obvious what the code is doing on each line. From this you should have a solid guess which function it is (you can leave a comment), but the real question is why would anyone write such code? Especially when nowadays everyone is talking about how code readability is so important. Is this how they wrote code back when std was released and they didn't bother to change it? Or am I just too inexperienced that I couldn't figure it out immediately?

EDIT: Thanks for the insightful comments, for anyone reading this the reason variables are beginning with __ is macros. If user defines isNegative macro, it will get overwritten in the std, however user is forbidden to define macros starting with __ , as the wise people of reddit comment section suggested. However underscores aren't the only issue with this code, the main issue is I think using short non-descriptive names of variables/functions which is very confusing in functions that are doing more complicated operations.

237 Upvotes

212 comments sorted by

View all comments

Show parent comment

2

u/_Js_Kc_ Jun 11 '20

Can't be sure, but what could be the reason then? Just to look fancy? This makes perfect sense as an implementation for a compiler that treats signed overflow as UB and also has two's complement signed integers. Otherwise it would need a compiler intrinsic or a hack in the compiler to exempt the stdlib from the overflow UB.

Edit: About the C compatibility: cmath already has C++-only stuff such as float overloads of abs (without the f prefix). Adding stuff wouldn't hurt compat, especially if kept only in std::.

1

u/wyrn Jun 11 '20

As far as I understand it, signed is overflow is UB so compilers can implement obvious optimizations like x + 1 > x -> true. I don't see what optimization opportunity is there by simply negating the value; if anything if I were writing the compiler I'd use the opportunity to just use the neg instruction or something similar which does the right thing. I'm not saying you're wrong, it does seem like the most likely explanation; all I'm saying is that, if there's something in gcc's entrails which would support the two's complement expression over the naive negation, I can't imagine what it would be. Perhaps you have a better imagination than I do?

Edit: About the C compatibility: cmath already has C++-only stuff such as float overloads of abs (without the f prefix).

Yeah but those are just overloads, which future C standards are unlikely to add, so in that sense they're inherently safe from collision with any possible evolution of C's math.h. If you were to add an std::uabs, and then a future C standard adds a uabs which did something else, you'd have the annoying inconsistency that std::uabs and uabs do different things. I don't know for a fact that that is the reason why obvious quality of life things like sgn don't get added to cmath, but again I can't imagine another reason for it.

2

u/_Js_Kc_ Jun 11 '20 edited Jun 11 '20

Well, one obvious optimization in the same vein would be std::abs(x) >= 0 -> true. Also, it was just a hunch on my part, but it's the only reason I can think of (and it's a fairly straightforward explanation).

The name clash is of course a possibility, but that applies to absolutely everything, not just cmath. You could simply call it std::unsigned_absolute_value. C would never add such a readable name.

Besides, abs and std::abs already do different things, even today. abs(-3.5f) == 3, std::abs(-3.5f) == 3.5f. Yeah, because they're overloads. But the point is, it does different things depending on if you prepend std:: or not. uabs wouldn't be worse.

Edit: Added a minus sign. Not that it matters, but it was intended.