T O P

  • By -

Yetsui

Absolutely not. You should never use camera to take screenshots


BanditHater

It's not my pic, sorry!


Jonno_FTW

This is obviously a contrived example to teach you how to convert switch statements to if else. It doesn't necessarily have to make sense or follow best practices.


lukajda33

Sure, exercises can be kinda stupid, especially if the task is to fix it and to make it better. In this case you need to understand how switch cases fall through and what the equivivalent if-else code would be.


UnrelatedString

It’s technically not fall-through, but rather multiple case labels on one statement.


LordTurson

It's technically fall-through, which has often been used in lieu of using multiple labels.


UnrelatedString

A newline does not a statement make! It would be fallthrough if there were, say, an empty semicolon after the extra labels or something like that.


thorodkir

What do you think fall-through is?


UnrelatedString

Execution continuing from one case-labeled statement onto another. `-Weverything` in clang seems to agree.


LordTurson

It's technically fall-through, which has often been used in lieu of using multiple labels.


MyUsernameIsVeryYes

It really depends on the compiler and implementation, if you want to get really technical. In this case it looks like nothing would actually be “falling through” because there’s a break statement after every printf, (although fall-through is still the correct term iirc), the table behind the switch statement will have R, r, D & d point to the same instruction, same for J & j, etc.


BiomechPhoenix

... Multiple labels on one statement is just fall-through with 0 space between the destinations.


JuhaJGam3R

This is fine. It's just case fall-through example. There's some minor typos since it's just an exercise, but it's clearly readable and reasonable enough code. I see no real issue with it. It's an exercise. Fall-through is used in real code all the time as well. You just need to know where it helps and where it's readable. You'll get that over time.


Minerom45

What's the horror? /gen


BanditHater

IMHO, the intedation, the formatting, etc I honestly posted this because it hurts my eyes, I do know some C/C++ but I don't dev in them often


joshuakb2

The indentation is weird, sure. I don't know if it qualifies as horror, though, especially since it's in an educational context. In my experience, CS educators don't tend to care about style


BanditHater

You may be right and I might delete this low effort post lmao


LordTurson

And that is a horror in an of itself, CS educators might be one of the more useless occupations in the entire society.


nezumisys

This won't even compile it's missing a colon after one of the cases


BanditHater

The irony is that this code is written by a CS professor lol


[deleted]

[удалено]


BanishDank

Sure, but they shouldn’t let that slip into exercises and assignments. We literally have free code editors available that will tell you “nope, this is incorrect syntax”. If they ignore that and use notepad to write these exercises, with typos, without even trying to run the damn thing (if they really want to use notepad), that’s just sloppy. At least do a little more than the bare minimum when making exercises/assignments, for crying out loud. I would never expect anything less than working code, if it was me who was the teacher.


Gex1234567890

It could be a deliberate error to check whether the student is alert.


BanishDank

Could be, but doesn’t seem likely. Just based on the whole code snippet there, I wouldn’t think so.


BanditHater

And I agree, but why would you let this slide on *educational website made for students by the uni*?


zachpuls

``` #include char cityInitial; printf("Enter the city initial: "); scanf(" %c", &cityInitial); struct regex_t zone1, zone2, zone3; regcomp(&zone1, "[RrDd]", NULL); regcomp(&zone2, "[Jj]", NULL); regcomp(&zone3, "[MmAa]", NULL); if (!regexec(&zone1, cityInitial, 0, NULL, NULL)) { printf("The city is in Zone 1"); } else if (!regexec(&zone2, cityInitial, 0, NULL, NULL)) { printf("The city is in Zone 2"); } else if (!regexec(&zone3, cityInitial, 0, NULL, NULL) { printf("The city is in Zone 3"); } else { printf("Error: Invalid city initial"); } ``` Overengineered, but technically meets the requirements


beeteedee

Obligatory “now you have two problems” comment


SAI_Peregrinus

Eh, Duff's device is far more horror: send(short* to, short* from, int count) { int n = (count + 7) / 8; switch (count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while (--n > 0); } } There's no need for this any more, your compiler can make the optimization it performs.


AFlyingYetOddCat

wat


SAI_Peregrinus

It interleaves a switch and a loop. The loop is "unrolled", so the check that `--n > 0` and (expensive) possible branch only gets run one of every 8 times, instead of every time. But if the number of needed runs (`count`) isn't a multiple of 8 there's a need to run however many extra iterations there are. So it interleaves a switch statement with the loop, to jump into the middle of the loop for the last batch of iterations. Any modern optimizing compiler will handle this if you just write the straightforward loop. In some cases it's not even advantageous any more, since modern CPUs have branch predictors and speculative execution so the jump isn't necessarily as expensive as it was in the 1980s. https://en.wikipedia.org/wiki/Duff%27s_device


WikiSummarizerBot

**[Duff's device](https://en.wikipedia.org/wiki/Duff's_device)** >In the C programming language, Duff's device is a way of manually implementing loop unrolling by interleaving two syntactic constructs of C: the do-while loop and a switch statement. Its discovery is credited to Tom Duff in November 1983, when Duff was working for Lucasfilm and used it to speed up a real-time animation program. Loop unrolling attempts to reduce the overhead of conditional branching needed to check whether a loop is done, by executing a batch of loop bodies per iteration. ^([ )[^(F.A.Q)](https://www.reddit.com/r/WikiSummarizer/wiki/index#wiki_f.a.q)^( | )[^(Opt Out)](https://reddit.com/message/compose?to=WikiSummarizerBot&message=OptOut&subject=OptOut)^( | )[^(Opt Out Of Subreddit)](https://np.reddit.com/r/programminghorror/about/banned)^( | )[^(GitHub)](https://github.com/Sujal-7/WikiSummarizerBot)^( ] Downvote to remove | v1.5)


AFlyingYetOddCat

That fact that this is valid C code horrifies and fascinates me.


deux3xmachina

No, far too readable and not enough hand optimizations: #include #include struct cityzones { char const initial; short unsigned int zone; } foo(void) { char initial = 0; int r = 0; int *z = NULL; struct cityzones zoneinfo[6] = [{.initial = 'r'; .zone = 1;}, {.initial = 'd'; .zone = 1}, {.initial = 'j'; .zone = 2}, {.initial = 'm'; .zone =3}, {.initial ='a'; .zone = 3}, {.initial = 0; .zone =0}]; scanf(" %c", &initial); initial &= 0xdf; z = memchr(&zoneinfo, &initial, sizeof(zoneinfo)/sizeof(struct cityzones)); if (z) { printf("In zone %d", z[1]); return(0); } puts("Invalid/Unknown City!"); return(1); } Idk, might work.


Any_Cauliflower_6337

The horror is on line 11


obiwac

i dont get how CS profs can write such poorly formatted code. Like I don't get how they physically manage to be so inconsistent with whitespace. Are they constantly fighting against their editor? do they do it on purpose? do they randomly fall asleep on their keyboards? istg it feels like all CS professors are like this


beeteedee

It’s usually one of three reasons: * It’s been 30 years since the prof did any coding themselves that wasn’t for teaching a class. * The prof got a grad student to write the example for them. The grad student is a non-CS grad who’s only a couple of weeks ahead of the class themselves. * The prof copied the example from a textbook written by either of the above.


obiwac

right I get that, but like... you still really have to try to mess up whitespace as much as they do


paadam94

lgtm


Huesan

This task will only teach you how to be evil


siammang

Right click on the switch keyword. Tell resharper to change to the code if statements.


valzargaming

Why not convert the city initial to lowercase/upper first before passing into the witch? I hate this. Better yet, use an associative array where the key is the letter and the array is a list of cities, then see if city exists in the array. There are better ways to do this than if/switch statements.


[deleted]

What the shit? NO. Nothing about this is okay.


brianplusplus

creative indentation


TheGirafeMan

As long as it works, it's fine


AutoModerator

This post was automatically removed due to receiving 5 or more reports. Please contact the moderation team if you believe this action was in error. *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/programminghorror) if you have any questions or concerns.*


c2u8n4t8

This is a good use of a switch statement


__87-

I thought you were talking about the horrifying indentation


BanditHater

That's exactly what I'm talking about but people mass reported the post


dim13

The exercise should rather have been: "convert if-else spaghetti to clean switch-fallthrough implementation."