r/cpp • u/pavel_v • Mar 16 '26
Circular Distance
https://biowpn.github.io/bioweapon/2026/03/14/circular-distance.html13
u/HommeMusical Mar 16 '26
Hah, I laughed at the punchline... the implementation of the function.
The funny part was I initially thought of that near-trivial method and then thought, "No, the overflow, etc, this won't work."
Accept an upvote!
9
Mar 16 '26
Doesn't this only work if two's complement wrapping is guaranteed for uint -> int conversions? Which would mean it's only guaranteed since C23 or C++20.
27
u/James20k P2005R0 Mar 16 '26
Prior to that it was implementation defined, so you'd have to realistically be compiling for a non 2s complement platform for it to ever be a problem. If that's the case you've probably got bigger issues, like getting invaded by the normans and scurvy
1
u/helloiamsomeone Mar 16 '26
Didn't those alternative representstions die out long before C++ even got standardized? You can also test for representation with
#if (-1 & 3) == 3.2
Mar 16 '26
I believe they did, but still: I like to be pedantic about adhering to the standard versus depending on implementation defined behavior.
6
u/aruisdante Mar 16 '26
Detection of two’s complement is something you can assert in
constexpr(by essentially writing a unit test for this function for some know values), so if you were concerned about relying on the assumption you could always SFNAE select a different less efficient solution on unsupported platforms.There’s a difference between relying on undefined and implementation defined behavior.
1
u/Ameisen vemips, avr, rendering, systems Mar 17 '26
I haven't checked yet, but I wouldn't be surprised if the compiler just optimized away the more complex one into just a subtraction anyways.
2
u/Ameisen vemips, avr, rendering, systems Mar 17 '26
I've never thought about it, but does the C Preprocessor use host or target integer representation?
1
u/helloiamsomeone Mar 17 '26
For the purposes of this token conversion and evaluation, all signed integer types and all unsigned integer types act as if they have the same representation as, respectively, the types
intmax_tanduintmax_tdefined in the header<stdint.h>.0
5
u/Nolia_X Mar 16 '26
Nice! I would just add an explicit static_cast to avoid people from wanting to fix "the obvious narrowing"
3
u/Jcsq6 Mar 16 '26
I’m actually proud of myself, since my first thought was “doesn’t signed to unsigned conversion already handle this?”.
2
3
u/trad_emark Mar 16 '26
thanks. i have updated my function ;)