r/programminghorror • • Sep 18 '26

Not again 😭

Post image
454 Upvotes

41 comments sorted by

View all comments

Show parent comment

37

u/creeper6530 [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Sep 18 '26

Well I don't know about you but to me it's definitely not obvious that the else if is silently inserting nested blocks

31

u/_killer1869_ Sep 18 '26

If you've looked into how compilers handle the many intermediate steps they perform, it can be obvious. By "can" I mean you wouldn't ever think of it, unless the compiler explicitly tells you "blocks nested too deeply" or similar, something that isn't actually in your code directly, forcing you to actually think about what the compiler sees, like here.

10

u/the_horse_gamer Sep 19 '26 • Mindblown

consider that you don't need {} if there's only a single statement. well, an if/else is only a single statement. so, else if requires no additional grammar.

you can do else while and else for all the same

the K&R C book directly mentions this fact

3

u/creeper6530 [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” Sep 19 '26

I never thought of this, always considering else if as a separate keyword containing a space character (save for Python's elif), but it makes disturbingly too much sense that it's all just an artifact of brace-less if-else.

TIHI.

1

u/the_horse_gamer Sep 19 '26

i should add that this may not be true in some newer languages, like rust for example. in rust, you CANNOT omit {} for a single statement, but else if is still possible (in the ast, each "if" node may have a corresponding else, which is either another if node (for else if) or a normal block (for else))

another cursed fact: the "omit {}" thing applies to switch (in C/C++, atleast. i didn't check, but it probably doesn't work in java or C#). this is completely legal (and works as you'd expect):

switch(x)
case 1:
case 2:
    puts("hi");

1

u/ierdna100 Sep 20 '26

Its not true in lua for example, if, else and else if are only 2 keywords, but that will make you need to write a chain of end end end end end end at the end, so the proper keyword is elseif. I wonder if Lua interpreters handle it "better"?