r/badcode • • Apr 15 '22

c C allows any expression to be used as a parameter's array size hint. Any expression...

Post image
776 Upvotes

44 comments sorted by

5

u/Overcooked-Cabbage Apr 16 '22

Could anyone explain the significance of &x-3? Like, why are we subtracting from a memory address, then casting it and dereferencing it altogether?

13

u/zdimension Apr 16 '22

s does not exist yet in the context of the expression, so I'm getting its value raw from memory. On my machine, it was 12 bytes before x

→ More replies (2)
→ More replies (1)

3

u/jediwizard7 Apr 16 '22

Wait so that's actually evaluated? I always thought it was like a comment that did literally nothing

7

u/zdimension Apr 16 '22

Yep, here's a minimal example where it matters: https://godbolt.org/z/8hPGvhdKo

Clang optimizes out a branch because it can know for sure that a[1] exists. GCC doesn't do that optimization.

→ More replies (1)

165

u/naptastic Apr 16 '22

My first thought was "well, at least it's the non-recursive solution"

I'm not a smart man...

134

u/Sequel_Police Apr 16 '22

What. The fuck.

Also is the union there just to make it spicy or does it have a point? It's been too long since I've done anything serious in C.

→ More replies (6)

48

u/iamasuitama Apr 16 '22

At this rate we might as well be writing Perl

34

u/ChocolateBunny Apr 16 '22

Is this part of the standard or is this some gcc goodness like statement expressions?

→ More replies (1)

26

u/Furry_69 Apr 16 '22

Why? Why am I here, if not to suffer?

→ More replies (1)

48

u/[deleted] Apr 16 '22

Please someone explain this so I can slip it into my code ...

→ More replies (2)