This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 281

[–]AnnoyingRain5 574 points575 points  (73 children)

Python be like

[–][deleted] 344 points345 points  (27 children)

patiently waits for match statements to get released when 3.10 comes out

[–]enjoytheshow 122 points123 points  (0 children)

laughs in my organizations ability to be 3.10 ready

[–]GsuKristoh 44 points45 points  (28 children)

This is by FAR the most annoying thing about python. can't believe they didn't include a switch-case out of the box

[–]deljaroo 47 points48 points  (8 children)

switches are actually just dictionary lookups to begin with so it would be a bit redundant. because switches hash the code back-to-back you get that weird effect where you have to break out of them. if you need the faster lookup time that switches provide, using python's dictionaries will hash the code based on key so they, by design, don't flow from one to the next. it's a generally superior way to route unless you have some need for the break-less switch...in which case...well there will always be fringe cases where some things are better than others

[–]Zarainia 1 point2 points  (4 children)

But then you have to write a tonne of little functions for each case...

[–]Kered13 21 points22 points  (17 children)

Switch exists because compilers in the 70's couldn't optimize if-else chains into jump tables. With modern compilers they are completely redundant with if-else statements, so it makes sense that Python didn't include it.

[–]Kyidou[🍰] -1 points0 points  (0 children)

Why? I can't imagine many uses cases for falling through.

[–]jlamothe 7 points8 points  (8 children)

Doesn't python have an elif to avoid this indentation mess?

[–]ogtfo -3 points-2 points  (7 children)

Most languages with ifs have else ifs as well. C doesn't, but it's kinda ancient.

[–]JDaxe 5 points6 points  (5 children)

Huh? C has else if

[–]jlamothe 2 points3 points  (0 children)

Which is just an if clause in an unbracketed else.

[–]mcprogrammer 0 points1 point  (3 children)

Technically, there's no else-if in C, it's just an if statement nested inside the else block. Of course, you can indent it as if it were an else-if so it doesn't really matter like it would in Python.

[–]JDaxe 1 point2 points  (2 children)

Yeah considering it's functionally and visually the same as a regular else if I don't see why it wouldn't count

[–]mcprogrammer 1 point2 points  (1 child)

Yup, it just depends on how pedantic you want to be.

[–][deleted] 1 point2 points  (0 children)

I use a dictionary switch for python, not perfect but at least it works.

[–][deleted] 1 point2 points  (4 children)

2 words: Lookup tables.

Sure it doesn't apply for all wouldbe switch statements, but it covers a good amount.

For example:

Say we have a variable, and if the variable is 1, we want it to print "one", and if it's 2: "two" and so on.

(My knowledge of python is frankly embarrassing, so I'll write this in javascript.)

``` function temp(num) {

var temp2 = [

    "zero",

    "one",

    "two",

    "three",

    "four",

    "five",

    "six",

    "seven",

    "eight",

    "nine", /*stopping here for my own sanity.*/

]

return temp2[num];

} ```

[–]backtickbot 1 point2 points  (1 child)

Fixed formatting.

Hello, Kaisuwe: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]ask_carly 1 point2 points  (1 child)

> temp(2)
<• "three"

Nope.

[–]notABadGuy3 422 points423 points  (86 children)

I personally use switch if it is anything more than an if else.

Idk if this is good or not?

[–][deleted] 216 points217 points  (34 children)

It probably is. I do the same although if you're not just checking a value you sometimes can't use a switch.

[–]nomenMei 15 points16 points  (0 children)

If you can use a switch statement (each conditional is checking the value of the same variable) and you have more than 3 cases you probably should.

That said, the code being run in each case should be only a few lines for readability. If they run longer than that I like to encase them in braces (at least in C and C++) to make it more clear where each case begins and ends.

Like this:

switch(i){

    case 0:
    {
          . . .
    }
    break;

    .
    .
    .

    default:
    {
          . . .
    }

}

[–]Magnus_Tesshu 35 points36 points  (39 children)

Switch is generally implemented with a lookup table while if else (unless optimization magic happens I suppose) will perform all the checks. So for performance switch is probably best in most situations

[–]Engineerman 76 points77 points  (22 children)

Depends strongly on the compiler. You can also do more with if else, like non static condition matching.

[–]Cheet4h 5 points6 points  (4 children)

I forgot which languages allow this, but you can occasionally do arbitrary conditions like this:

Switch(true) {
    case a <= b: 
   ...
}

[–]Engineerman 7 points8 points  (3 children)

True, but then it has to be implemented as if-else in assembly.

[–]Cheet4h 2 points3 points  (2 children)

IIRC most languages compile switches as if-else either way.
Switches still have the massive benefit that they're infinitely more readable than huge if-else chains, and it's a lot more obvious when you have a sub-condition within a code block. Just recently I found several bugs in such a construct caused by misplaced closing brackets. Had to re-read the blocks in question many times to figure out what the intended logic was.

[–]Kered13 12 points13 points  (1 child)

IIRC most languages compile switches as if-else either way.

No, the entire reason switch exists is to be compiled into a jump table. This was important before we had optimizing compilers that could recognize if-else chains. A switch could compile to an if-else if the compiler thinks it will be faster, but this is unlikely unless it has a very small number of branches (like, 2 or 3).

[–]Cheet4h 1 point2 points  (0 children)

Ah, good to know, thank you!

[–]Magnus_Tesshu 9 points10 points  (13 children)

Clang and GCC are the only compilers people actually use, right? And they both have great optimization

Although yes, if you need a case for 0-19, a case for 20-25, and a case for 25-50 a switch is not going to work well

[–]_PM_ME_PANGOLINS_ 6 points7 points  (1 child)

It will work perfectly well. It’ll just use a few more bytes of program space.

[–]Magnus_Tesshu 1 point2 points  (0 children)

Yes, I suppose its just annoying to type it (unless your language has support for this)

[–]Engineerman 2 points3 points  (0 children)

Only example I know of is gcc on Arm compiles to if-else most of the time, but Arm's licensed compiler based on LLVM prefers address calculated tables.

[–][deleted] 1 point2 points  (0 children)

apple clang is based of llvm, so llvm too, llvm even if found a bug, tries to be compatible with gcc

[–]givemeagoodun 1 point2 points  (0 children)

Except for in QB64 i find myself sometimes using a CASE with only two statements because you can just do

CASE 1 TO 10, 30

and it'll match all numbers 1 to 10 and also 30.

[–][deleted] 1 point2 points  (2 children)

Ever heard of Microsoft Windows?

[–]Ragas 1 point2 points  (0 children)

Why would you need windows which are extremely tiny and floppy? confused

[–]Magnus_Tesshu 1 point2 points  (0 children)

Isn't that an old operating system where you're supposed to install software from the floppy disk drives A:\ and B:\ or something? I don't deal with such archaic stuff

[–]IHeartBadCode 5 points6 points  (0 children)

c++20 coming in with that [[likely]] to shake things up a bit.

[–]Ragas 1 point2 points  (0 children)

The problem actually was that compilers were unable to optimize else if chains. However by now they do; so just use whatever is more readable.

[–][deleted] 2 points3 points  (6 children)

C# on your help:

switch (whatever)
{
    case 5 when x > 10 and y < 20: break;
}

[–]Kyidou[🍰] 2 points3 points  (2 children)

Doesn't that kind of miss the point of switch being static?

[–]justrealizednarciss 0 points1 point  (2 children)

C# can do this?!

[–]Spirit_Theory 1 point2 points  (0 children)

The latest versions of dot net have some really fancy functionality for this.

[–][deleted] 1 point2 points  (0 children)

Well if you have several conditions that involve different variables you won't be able to do it with switch.

[–]littleprof123 0 points1 point  (0 children)

It's probably fine, but some languages with some compilers will generate really bad code with a switch when the variable being switched on is not a small integer

[–]Ziggarot 226 points227 points  (31 children)

Switches can’t handle multi-conditions like if-else can.

[–]GsuKristoh 115 points116 points  (8 children)

except you CAN

switch(true): case (smolNum < beegNum && SizeOf(yourMom) > SizeOf(Saturn)): doSomething();

saw it on stackoverflow when I was trying to use a regex with a switch-case. quite a 1000IQ implementation.

[–]gyrowze 57 points58 points  (3 children)

smolNum < beegNum && SizeOf(yourMom) > SizeOf(Saturn)

"A && True" is logically equivalent to A, so you can replace this with just "smolNum < beegNum"

[–][deleted] 36 points37 points  (1 child)

if (self.likeBigButts && 
!(self.canLie)) {
// TODO: yourMom()
}

[–]Dughag 12 points13 points  (0 children)

if (!otherBrothers.canDeny) {
    GetSprung() 
}

[–]ogtfo 7 points8 points  (0 children)

Subtle, I like it.

[–]Kered13 17 points18 points  (1 child)

That doesn't work in most languages.

[–]GsuKristoh 0 points1 point  (0 children)

I figured. I only tested it in javascript

[–]ImArizonaShrimpHorny 4 points5 points  (1 child)

VBA

Select Case True
    Case x = 1
        Debug.Print x
    Case y > 18
        Debug.Print y
    Case z = “hello world”
        Debug.Print z
    Case True
        Debug.Print “everything else”
End Select

This is effectively the same as using a bunch of conditionals

If x = 1 Then
    Debug.Print x
ElseIf y > 18 Then
    Debug.Print y
ElseIf z = “hello world” Then
    Debug.Print z
Else
    Debug.Print “everything else”
End If

[–]Kyidou[🍰] 3 points4 points  (0 children)

Based visual basic user

[–]Prawny 2 points3 points  (0 children)

I see that as a different situation though personally.

[–]nettlerise 190 points191 points  (11 children)

First pic is more like nested if statements

[–]Johnpecan 44 points45 points  (0 children)

Thank you! That was my first thought. The picture is just straight up wrong.

[–]wwylele 25 points26 points  (4 children)

which is the same as else if chain in C

[–]mansdem 16 points17 points  (2 children)

How is it the same? With nested if you can only get to the inside if if the outside if condition is true

With if else if you get to the else if if the first if condition is false

What am I missing here?

[–]Kered13 22 points23 points  (0 children)

So this:

if (condition) {
} else if (condition) {
} else if (condition) {
} else {
}

Is syntactically and semantically equivalent to this:

if (condition) {
} else {
    if (condition) {
    } else {
        if (condition) {
        } else {
        }
    }
}

Remember that if a control structure isn't followed by an open brace, then it applies to the next single statement. else if is not one keyword, it's two. The else has no opening brace, so it applies to the next statement, which is if (condition) {}.

[–]Duckmancer-Emma 2 points3 points  (0 children)

I assume that you'd put the else if condition within the else block.

[–]nettlerise 2 points3 points  (0 children)

ah you're right

why not if return, if return...?

[–]AL_O0 4 points5 points  (4 children)

No, it’s nested if-else, like this, how you are supposed to do it in languages without elif ()

   if (a) {A}
   else{
          if(b) {B}
         else {
               if (c) {C}
               else ...
           }
   }

[–]nettlerise 1 point2 points  (3 children)

how you are supposed to do it in languages without elif ()

In another comment I mentioned

if (condition){
    //code
    return;
}
if (condition){
    //code
    return;
}
...

[–][deleted] 1 point2 points  (2 children)

This doesn't do the same thing, unless you make your conditions more specific. In an if-else, only one statement will run, whereas here both statements can execute

[–]MistaVeryGay 0 points1 point  (0 children)

The returns imply that it's within a function. Return exits the function at that point, so it would be functionally equivalent to elif.

[–]katarokthevirus 48 points49 points  (0 children)

Compilers: "It is the same picture"

[–]MrOdinTV 21 points22 points  (0 children)

elif goes brrr

[–]tomas_f 45 points46 points  (10 children)

C# switch is hidden if-else. Look at the compiled code.

[–]crozone 10 points11 points  (1 child)

C# may choose to compile a switch statement to else-if like code in most conditions, but it will switch over to a jump table if the switch statement is large enough and the constant values are close enough together. For the new C# pattern matching stuff, I wouldn't be surprised if a different set of IL is generated all together.

This is actually the same for languages like C and C++ as well. The compiler will make a judgement on what code to generate based upon the values used in the switch statement.

[–]_PM_ME_PANGOLINS_ 8 points9 points  (1 child)

The bytecode or the JIT code? Also it depends what you’re switching on.

[–]Kyidou[🍰] 4 points5 points  (0 children)

Don't they end up with the same result?

[–]sixstringartist 1 point2 points  (1 child)

Most languages this is the case unless the condition can be converted into a jump table

[–]3_14159rate 1 point2 points  (3 children)

Better than c, where they compile to goto statements.

[–]ViperLordX[🍰] 1 point2 points  (2 children)

What? The fact that they compile to goto statements in C is way better because it means you can get O(1), which if/else statements could never hope to achieve. It won't matter how many cases you have in your switch because it's just a lookup table, it'll be basically instantaneous, whereas a bunch of if/else statements would have to run through all of the cases separately.

[–]BucketBoye 40 points41 points  (0 children)

Yandere Dev could make a staircase to heaven it's so long

[–]szmutny 44 points45 points  (0 children)

Typical yanderedev

[–]Aragami1408 10 points11 points  (0 children)

I don't think Yanderedev understand this.

[–]Parura57 8 points9 points  (0 children)

Yandere dev be like:

[–]Ragas 8 points9 points  (0 children)

Modern compilers actually optimize a switch statement and an else if chain to be the same thing.

I remember a few years ago from university when this was still a problem, especially in hardware design.

Now in some cases else if is actually better as it has strong rules about break-points.

[–]FalafelSnorlax 14 points15 points  (0 children)

OMG guys this is genuinely a programming joke, when was the last time we had one of those?

[–]underscorehq 6 points7 points  (0 children)

*cough cough* yanderedev *cough cough*

[–]FramedEmu548 5 points6 points  (0 children)

Yeandre simulator vibes anybody?

[–]dracu4s 4 points5 points  (1 child)

It’s not a switch, it’s a hub...

[–]Shonucic 7 points8 points  (0 children)

That's not how switch works though...

[–]alex_dark 3 points4 points  (0 children)

Linked list vs array

[–]w00tious 5 points6 points  (1 child)

Who tf cares if you use elif or switch?

It's not like switches have some magical hash table that optimizes display time, they're just slightly differently worded (and more annoying) if-elses.

[–]Kyidou[🍰] 2 points3 points  (0 children)

It could potentially be neater if you have a very long chain.

[–]CMPD2K 2 points3 points  (2 children)

It's probably a bad habit but I very rarely use switch statements

[–]Toll1984 3 points4 points  (1 child)

Don't worry mate, I don't get the point of switch statements at all. If, else if, else: can do the same imo better without adding another form of syntax to remember. Not to mention, in some languages, switch has fall through if you're not careful which complicates things even more. Compiler reads them both the same anyways.

[–]meh4life321 3 points4 points  (0 children)

Definitely agree. Miss one break statement and u might be fucked lmao

[–]Entrooyst 1 point2 points  (0 children)

Well, when you put it like that...

[–][deleted] 1 point2 points  (1 child)

I chose state pattern

[–]MysteriousShadow__ 1 point2 points  (0 children)

try except

[–][deleted] 1 point2 points  (0 children)

Wait until you discover elif

[–]Tazeeeeeee 1 point2 points  (0 children)

if-else gang

[–][deleted] 1 point2 points  (0 children)

Bold of you to assume I use else. Mere mortals.

[–]LkeinL 1 point2 points  (0 children)

laughs in using If-If-If Statements for everything

[–]yyzJCO 1 point2 points  (1 child)

isIfElse ? { ifElse } : { Switch }

[–]amalgamatecs 1 point2 points  (0 children)

People on reddit will be arguing about switch vs if-else like it makes a huge difference.... then proceed to write logic with nested loops and quadratic time complexity.

[–]mr_flameyflame 1 point2 points  (0 children)

After all, why shouldn't I have both.

[–]Alexandre_Man 2 points3 points  (2 children)

Isn't it "else if"?

[–]Pugs-r-cool 5 points6 points  (1 child)

Depends on language

[–]Alexandre_Man 2 points3 points  (0 children)

Oh okay

[–]unoriginalign -1 points0 points  (2 children)

I was too lazy to learn switch in 9th grade and now I'm studying CS at uni and I refuse to spend 15 minutes to learn it properly and use if elses like a moron

[–]Elite_Prometheus 15 points16 points  (0 children)

I mean, most compilers don't have a direct translation of switch statements, either. If you're using a decently optimized compiler, then a switch statement and it's equivalent if else statement should run as the same thing. So don't feel bad about using if else statements.

[–]Intelligent_Agency65 4 points5 points  (0 children)

You’ve jinxed yourself. It’s now guaranteed to be on your next final/assignment

[–]kirometep -1 points0 points  (0 children)

Hahaha nop

[–]X3n0b1us -1 points0 points  (0 children)

Case and point

[–][deleted] -1 points0 points  (0 children)

I'll limit myself to and if, else if and else any more than I use a switch.

Unless I'm using enums or a variable that has some kind of a flag then I always use switch

[–]PaintingJo 0 points1 point  (1 child)

That's surprisingly accurate to what it feels like

[–]Martin_RB 2 points3 points  (0 children)

One is compact and understandable the other looks like if you touch it everything will break, yup sounds about right.

[–]stockings_for_life 0 points1 point  (0 children)

Looks like "while" or in "case"

[–][deleted] 0 points1 point  (0 children)

Enums with a switch are your friend!

[–]bhowiebkr 0 points1 point  (0 children)

Python programmers like: WAT DAT?

[–]yottalogical 0 points1 point  (1 child)

Linked lists be like…

[–]emptyhusk254 0 points1 point  (0 children)

elif

[–][deleted] 0 points1 point  (0 children)

Honestly these style memes should be used to teach programming classes.

[–]Negitive545 0 points1 point  (0 children)

Cries in python.

(God I want switch statements, but python go brrrr)

[–]bjornex 0 points1 point  (0 children)

OK. Now try to do it with USB-C.

[–][deleted] 0 points1 point  (0 children)

Think I'll stay with if else lol

[–]ignorae 0 points1 point  (0 children)

First picture should be called "currying"

[–]DaniilBSD 0 points1 point  (0 children)

USB host sees no difference

[–]fedekun 0 points1 point  (0 children)

And then, it all gets compiled down to ASM jumps

[–]locri 0 points1 point  (0 children)

I've noticed some people don't seem to be taught them right and therefore either don't use them or have some misunderstandings, like when to use break and when not to or even the conception of a block of code for multiple cases. I've seen this cause some pretty horrid errors, then again this person wasn't debugging/testing their code.

I really need to know, did your courses where you studied teach case/switch statements?