News for hackers. Stuff that matters.
Re:Using ‘switch’ to match arbitrary logic instead of string... by jbverschoor on Monday August 19, 2019 @08:08AM (#20737015)
>> A switch statement does not allow this. True, but a compiler will detect unreachable code when you do:

  if (x) {
  else if (x) {
    // warning
  }


>> My philosophy is always to write code that expresses as much as possible its intent agreed

>>, and the sequence of operations the computer has to take. From a performance perspective yes, from a logic / maintanance perspective not really.

Re:Using ‘switch’ to match arbitrary logic instead of string... by w0utert on Monday August 19, 2019 @10:55AM (#20738273)
>> True, but a compiler will detect unreachable code when you do

Interestingly, neither clang nor g++ give a warning for this case:

  int main(int argc, char **argv)
  {
    int x = argc;
  
    if (x == 0)
    {
      x = 10;
    }
    else if (x == 1)
    {
      x = 20;
    }
    else if (x == 0)
    {
      x = 30;
    }

    return 0;
  }

  # g++ bla.cpp -o out -Wall
(no warning)

  # clang bla.cpp -o out -Wall
(no warning)

I assume this is because the compiler can never be 100% sure a variable cannot be changed midway through testing each of the conditions because of aliasing, so it won't throw a warning. In this particular example this obviously is not relevant, but I can imagine some pathological example where one of the tests has side effects that change the result of the later tests, and to avoid false positives the compiler simply never warns about unreachable code for these things.

In a sense, this is exactly what I mean by writing code that matches exactly what you want to happen. If I write 'switch (x)', it's pretty clear the test is executed exactly once. If I write a sequence of if-elseif-elseif-else statements, the conditions are evaluated in sequence, which is not what I want.