Hacker News new | past | comments | ask | show | jobs | submit login

Just remove the `static` keyword and there you go.

But it's an "optimization", and avoiding previously attempted methods is the whole point of the trick. Otherwise it would be an easy and uninteresting function.




> Just remove the `static` keyword and there you go.

That‘ll probably try all methods on every single file that is processed, so if method #16 is the one that works, you get 15 unnecessary syscalls for every file.


Exactly, that's what the parent comment was saying.


Lets say that there are only 3 methods and method #2 is the one that works initially. On the first call it'll try #1 and when that doesn't work it'll try #2 which will be successful. For the next however many calls it'll jump straight to #2. If #2 starts returning ENOSYS at some point it'll try #3 and if that works then all future calls will jump straight to #3. However if #3 stops working then it will keep on failing until #3 starts working again even if #1 started working after the first call.

I think (I haven't actually tested it) you can do what the parent commenter wants by wrapping the whole thing in a do-loop but the original implementation is questionable enough, sticking an extra loop in there isn't doing anything to help make it less horrible.

  int set_the_mtime(...) {
    static int switch_step = 0;

    int loop_again = 1;

    do {
      switch (switch_step) {

      case 0:
        if (method_0_works(...))
          return 0;

        switch_step++;
        /* FALLTHROUGH */

      case 1:
        if (method_1_works(...))
          return 0;

        switch_step++;
        /* FALLTHROUGH */

      case 2:
        if (method_2_works(...))
          return 0;

      }

      switch_step = 0;
    } while (loop_again--);

    return -1;   /* ultimate failure */
  }




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: