r/ProgrammerHumor 9h ago

Meme skillIssue

Post image
3.5k Upvotes

93 comments sorted by

1.5k

u/Xterm1na10r 9h ago

omg an actual original programming meme, even OC, thank you OP

579

u/SonicLoverDS 9h ago

No break statements? Amateur.

242

u/No-Newspaper8619 8h ago

give him a break

98

u/OliveBoi_ 8h ago

; expected

25

u/D3PyroGS 7h ago

give him a break,

give him a break,

break him off a piece of that syntax error

1

u/0bel1sk 1h ago

thanks, now i’ll be thinking of that tune all morning.

56

u/Extension_Option_122 4h ago
#define BREAK ;

Now you can add as many break statements as you like.

7

u/SuitableDragonfly 1h ago

And you can be evil and sometimes write BREAK instead of break in a real switch statement. 

20

u/click-to-reveal 4h ago

Well technically, each case has a break coz it's if-else. What is doesn't have is the lack of a break statement aka fall-through.

292

u/PixelatedGiant 7h ago

This is the kind of stuff you find in books with titles like...

C++ : Man made horrors beyond human comprehension 3rd Edition paperback

44

u/gil_bz 3h ago

This might be the mildest macro weirdness that I've ever seen, there are some true horrors out there.

25

u/bythenumbers10 2h ago

Ah, yes. The necroprogamicon, 13th ed. Author fed himself into a dot-matrix printer after finishing it in the 90s, IIRC. Shame, the guy had such marvelous visions to share. Only way to really understand C++, IMHO.

11

u/GroovinChip 1h ago

“Fed himself into a dot-matrix printer” feels like a Douglas Adam’s line lmao

12

u/l2protoss 2h ago

When I was younger in my career, I was a very “creative” dev - to the point where I was banned from using macros without explicit permission lol.

4

u/StCreed 52m ago

Hehehe my friends once used macros to facilitate pointer arithmetic. After a month they couldn't get anything to work anymore and had to start over with a new program :)

Good times!

2

u/whackylabs 35m ago

What is wrong with this code?

168

u/khalamar 8h ago

Reminds me of that guy who was asked to write C code, but he only knew pascal

First lines were

#define begin {
#define end }

And a few other horrors.

22

u/AvidCoco 3h ago

Some compilers define OR as || and AND as &&. The latter means you can write move constructors like

Foo(Foo AND other)

19

u/Possseidon 3h ago

Not just "some compilers", it's part of the C and C++ standard and any compliant compiler has to support it.

For C you have to include a builtin header with macros for them, in C++ it's actually just part of the compiler itself.

u/AvidCoco 9m ago

IIRC I think it’s more that some compilers implement that feature as a simple find-and-replace (like a macro) while others are more context aware and so don’t allow it in the way I described.

224

u/click-to-reveal 9h ago

It works btw: C++ Online Compiler

126

u/prehensilemullet 8h ago

Performancewise, it doesn’t jump to the direct case in O(1) time like a switch is supposed to though

165

u/AngheloAlf 8h ago

Switches aren't guarantee to so operations in O(1) tho. If cases are sparce enough, compilers tend to emit the equivalent code to a bunch if else checks

18

u/prehensilemullet 6h ago

Yeah I was assuming too much here.  However, I’m reading that Rust match on string comstants can compile down a binary tree of if statements if there are enough cases (according to Google AI mode at least, haven’t found an authoritative source yet)

15

u/Nir0star 4h ago

Which would still be O(ld(n)). But cool feature imo.

4

u/im_made_of_jam 3h ago

A switch case is able to be implemented however the compiler wants on the back end, so for sparse cases it'll be an if else chain, for less sparse but not packed cases it'll be a binary tree, for completely packed cases it'll be a range check then a direct jump would be how I would go about it

1

u/the_horse_gamer 1h ago

the compiler optimises stuff however it wants. if you're not doing too-weird stuff, a switch in C++ and a match in rust will have identical assembly.

-16

u/Deliciousbutter101 4h ago

According to Claude (which looked at the compiler source code), it doesn't seem like that is true. It is possible to get an O(1) match on strings by using the phf (perfect hash function) crate and by using the following macro (generated by Claude):

``` // Cargo.toml: // phf = { version = "0.11", features = ["macros"] } // paste = "1"

[macro_export]

macrorules! match_str { ($val:expr, { $($($key:literal)|+ => $body:block),+ $(,)? , _ => $default:block $(,)? }) => { ::paste::paste! { { #[derive(Clone, Copy, PartialEq, Eq)] enum __MatchStr { $($([<_ $key>]),+),+ }

            static __MATCH_STR_MAP: ::phf::Map<&'static str, __MatchStr> = ::phf::phf_map! {
                $($($key => __MatchStr::[<__ $key>]),+),+
            };

            match __MATCH_STR_MAP.get($val).copied() {
                $($(Some(__MatchStr::[<__ $key>]))|+ => $body,)+
                None => $default,
            }
        }
    }
};

} ```

Usage: fn apply(cmd: &str, counter: &mut i32) { match_str!(cmd, { "small" => { *counter += 1; }, "medium" => { *counter += 10; }, "large" | "big" => { *counter += 100; }, _ => { *counter += 0; }, }) }

7

u/DrMobius0 5h ago

In fairness, most switches probably use enums.

43

u/Deliciousbutter101 8h ago

O(1) only happens when the constants are (roughly) contiguous so it's not like that is a universal property of switch statements.

0

u/prehensilemullet 6h ago

Yeah that’s true

13

u/AsidK 7h ago

Any reasonable compiler will make a switch statement and its equivalent if else chain compile down to the same assembly

1

u/prehensilemullet 6h ago

Even if it could make a more efficient tree of comparisons for a large number of strings?

4

u/mirhagk 6h ago

What they are saying is that any optimization on a switch statement could also be done on an if statement. There's no reason to only optimize one, both should optimize the same way

0

u/prehensilemullet 6h ago

hmmm...are compilers normally willing to reorder if statements though? Turning a sequence of string comparisons into a tree would involve reordering

8

u/mirhagk 6h ago

If it has the same semantics, why not? Modern compilers certainly can see if a statement has side effects or not

1

u/prehensilemullet 6h ago

it depends what you consider semantically relevant. For instance, suppose the developer intentional ordered the if statements from the most to least common case for some domain. Then, reordering the if statements might not be what the developer wants

4

u/Infamous-Strategy797 6h ago

There aren’t any unknowns here, the language spec provides the clarity the compiler needs to re-order safely.

1

u/prehensilemullet 5h ago

Okay for C++, I gather that performing better or worse on a given dataset doesn't fall under the umbrella of "observable behavior" that the spec requires the compiler to preserve.

I also just learned there are apparently [[likely]] and [[unlikely]] attributes in C++ 20 that can be added to branches.

→ More replies (0)

1

u/guyblade 2h ago

At least in C/C++, there can only be exactly zero or 1 cases that match a switch (i.e., there's no range-based switch), the case values must be compile-time constants (and thus are not themselves evaluated during the comparison), and I'm pretty sure that the value to be matched is required to only be evaluated once (so the comparisons happen on an rvalue).

Given those constraints, I believe a compiler can assume that re-ordering the comparisons is safe.

1

u/AsidK 2h ago

> fallthroughs have entered the chat

2

u/guyblade 2h ago

You can still only match to one, though. In the emitted machine code, I'd expect to see a forest of branches and jumps (for the matching), then the various bodies of the cases each separated by jumps (representing breaks) as appropriate.

6

u/jacob643 8h ago

what? doesn't it need a "{" after the "if(0)" and please, why not if(false) ? :') edit: I'm stupid, it's written by the user/client of the switch

15

u/click-to-reveal 8h ago

if(0) coz that line (on mobile) was close to the right edge and no one like text wrapping in code :)

6

u/SuitableDragonfly 8h ago

if(0) is just more compact, I think. 

1

u/DrMobius0 4h ago

It may compile, but does the debugger avoid shitting itself when you need to set a breakpoint there?

Also, you can just write an enum and then map the enum to strings if you want a properly supported switch.

64

u/F100cTomas 9h ago

Just define a constexpr hashing function and put that into the switch.

28

u/GiganticIrony 9h ago

That’s not guaranteed to work due to hash collisions

25

u/Deliciousbutter101 8h ago

It won't compile in the case so you can just modify the hash function until there are no collisions.

9

u/SteveXVI 2h ago

This is the closest I've come to feeling like that guy in the Apple shop going "ah of course"

10

u/SAI_Peregrinus 8h ago

Use Blake3, no collisions in any practical workload in the next few billion years.

3

u/guyblade 2h ago

The thing about the pidgeon hole problem is that we know there are collisions, but we don't necessarily know where they are. The space of strings of at least 33 characters has collisions. There's no way to know or prove that arbitrary input doesn't have one with a value you care about.

u/remind_me_later 5m ago

If that happens, someone would post it to social media, and a list of exceptions can be added afterwards.

8

u/remind_me_later 8h ago

That’s not guaranteed to work due to hash collisions

Make the hashes 128/256 bits wide. Hash collisions are realistically impossible at those levels.

2

u/StCreed 49m ago

They're far more possible than you might think. Roland Bouwman wrote an article on MD5: In a large database you can't use MD5. And that's not petabyte size either, 100GB is enough to give you about a 50% chance of a collision.

u/remind_me_later 9m ago

Counterpoint: It's MD5, a known broken hashing algorithm.

SHA3_256 or regular SHA256 would work just fine.

u/StCreed 6m ago

yeah, because md5 is 128 bits. 256 bits works a lot better, but 128 is just not enough even with a better algorithm and assuming effectively random distribution.

4

u/Rabbitical 9h ago

I'd probably intern instead of hashfor a presumably known set of comparisons

3

u/ElectricalPrice3189 9h ago

And if it got a clash, guess what? It won't compile.

6

u/Thwy__ 9h ago

Yet, string switch in Java is also made using hashs

16

u/GiganticIrony 9h ago

Yes, but if there’s a collision, it then uses `.equals()`

1

u/SpiritedEclair 1h ago

Perfect hashing for a given set of values is possible at compile time.

It’s how compilers generate jump tables.

22

u/fluffycritter 7h ago

My "clever" way of doing this once upon a time was to declare a map<std::string,std::function> which I populated with lambdas and then evaluated.

I would not recommend this approach.

6

u/yuri_4_ever 4h ago

I have little idea of c++ why is this a bad idea?

9

u/fluffycritter 3h ago

It’s actually not too awful, but the syntax is a bit awkward, std::map lookup is slower than you think, and there’s a few gotchas with how lambdas work in terms of variable scoping. Also unless the map is being initialized once and kept around, you’re paying a lot of extra costs every time it’s called.

Usually a chain of if/else ends up being more performant, although I guess if you’re trying to switch on a text label instead of an enum or whatever you’re probably already doing something very wrong and using a map<string,function> is probably the least of your problems.

2

u/babalaban 1h ago

Also your std::function might allocate which is most likely not desirable. My "clever" workaround was to keep a static const map of string -> enum in a .cpp file initialized at compile time only exposing functionality via a lookup function in a header.

Standard map is usually made using binary search trees, so in terms os complexity they are faster. BUT in terms of real world speed they only become reasonable in cases where you have a huge amount of entires, due to cache misses that are inherit to RB trees.

I ended up changing mine to arrays of self-made pairs and just looping over it checking .key

7

u/Kiro0613 7h ago

Not a bad idea for a little CLI app though

10

u/fluffycritter 7h ago

Yeah it's actually how boost::program_options handles command-line arguments. It's nice for that, at least.

EDIT: Wait no I'm misremembering and confusing it with something else, never mind

14

u/ElectricalPrice3189 9h ago

Do a constexpr string hasher and it'll work.

4

u/SavingsCampaign9502 8h ago

Come on support break;

5

u/ForgedIronMadeIt 6h ago

This is almost as fucked as Duff's device but still theoretically useful.

3

u/JackNotOLantern 6h ago

I usually prefer if- else over switch. No risk of forgetting break, comparing to any type. I use switch almost exclusively for enum check.

3

u/gil_bz 3h ago

This is even better than a real switch, it supports non-const expressions!

4

u/ManonMacru 2h ago

Oh that's dirty. Syntaxic sugar for my syntaxic diabetes. 11/10

4

u/Greedy-Thought6188 8h ago

So we do know that those are not the semantics of a switch statement. In C a case falls through without a break. That monstrosity in actual code would be a firsble offense.

3

u/PhosXD 8h ago

Wait, W A T.

3

u/Denaton_ 5h ago

No fall thru

2

u/caiteha 9h ago

oh wow.

2

u/atomic_redneck 2h ago

Looks like there some issues with the scope of _s. Try putting two SWITCH statements in one scope block.

0

u/click-to-reveal 2h ago

You can always wrap it in braces if that happens.

1

u/americanov 3h ago

Bro though he's on SO

1

u/zoniss 2h ago

Pascal had native support for this

1

u/IUseClifford 1h ago

Whose \#define is it anyway? C++, where the syntax is made up and nothing matters

1

u/lmarcantonio 1h ago

The Real Programmer would know that (in C, the example is C++) a constant string is a pointer and a pointer is and integer. So you CAN switch on a constant string. Would it work? no, but it would compile.

1

u/pain_suffer 53m ago

I'd have used enum+hashmap+switch but this is waaaaay cooler.

1

u/whackylabs 30m ago

Looks like a lot of folks here are not familiar with Bourne Shell https://research.swtch.com/shmacro

1

u/cob59 10m ago

Since C++17 you even have optional init statements in ifs, so:

#define SWITCH(x) if (auto&& _s=x; false)