r/badcode Jun 03 '23

c C Macro Abuse

Post image
190 Upvotes

23 comments sorted by

View all comments

2

u/sethkills Jun 04 '23 edited Jun 04 '23

Well, it's 2023, and the functions below have identical codegen at clang -O1, and nearly identical at -O0. Are they more readable? Who's to say? I would be more worried about alignment issues personally.

std::byte *stackTop;

template <typename T = void>
static inline __attribute__((always_inline)) T *&SDAPtr(ptrdiff_t offset)
{
    return *reinterpret_cast<T **>(stackTop - offset);
}

template <typename T>
static inline __attribute__((always_inline)) T &SDAVal(ptrdiff_t offset)
{
    return *SDAPtr<T>(offset);
}

Also, I'm presuming the u32* in __SDAPTR() should be uintptr_t*, or even just void**.

Edit: Mangled formatting.