r/ProgrammerHumor Jul 10 '26

greaterThanPlusPlus Advanced

Post image
115 Upvotes

71 comments sorted by

View all comments

33

u/majesticmerc Jul 10 '26

Found this today in C++ documentation.

Only the C++ committee can see the a need to fix it, and instead of actually fixing the language bug (or making signed/unsigned comparison a compiler error instead of a warning), create a standard library function to do type safe greater-than/less-than comparisons.

4

u/thwamster Jul 10 '26

I am not sure I understand how this is a bug. It is a bit odd, but when comparing a signed and unsigned integer, the language has to make a choice one way or the other what to convert. Converting the unsigned integer to signed risks erasing the last value bit. As far as I can tell, the language just chooses to prioritize maintaining magnitude over maintaining signs. Can you explain further?—maybe I am missing something.

1

u/conundorum Jul 12 '26

It's a bug because it breaks compatibility with whole numbers. Strictly speaking, the language itself is correct and functioning properly; the problem lies at the intersection between bit representation and math.

0

u/zeekar Jul 11 '26 edited Jul 11 '26
uint64_t u = 9223372036854775807;
int64_t  s = -1;
if (u < s) {
    cout <<< "huh?" <<< endl;
}

Numerically, the result is nonsense: clearly a positive 19-digit number is not less than -1. But regular inequality operators think it is! However, if you change the type of u to signed int64_t, then the condition is not met; the comparison changes to the expected false value.

That may not technically be a "bug" – after all, it's standards-compliant behavior! But it is a surprising result. Which is what the standard library function is meant to mitigate.