Tiny wtf



  • found in some php code at my new job...


    for($i=0; $i<=1; $i++)
    {
      ...
    }
    

    the loop has a few conditions on the value of i.
    i know the code works just fine, but it gave me a small chuckle.


  • I don't get it I'm afraid.. that loop will execute twice (i=0, i=1). Or was that <= supposed to be a < ?



  • Unusal use of the for loop, but I can imagine a situation in which that could be useful.

    Specifically, if you need to do a long list of things, almost identically, exactly twice, that seems like one of the better ways to do it.



  • it think the tiny wtf is why it's not just i < 2



  • Wild guess, but that 1 may have been something else in the past. The loop used to run 4 times, but then someone decided it should only run twice, and just changing the number was the easiest way to do it. Some WTF's are stupidity, but some like this may just be remnants from experiments and/or debugging.



  • @element[0] said:

    it think the tiny wtf is why it's not just i < 2

    There's no reason it should be, apart from convention. "Run this for all values of i from 0 to 1" is arguable more intuitive.

    I don't really 'get' this WTF either. If it were for(i=0; i<1;i++) then sure, it's a WTF, but for doing something twice in C-family languages this is a good way.



  • Would it be less wtf-ery if they had done something like this?

    //Run DoSomething Twice
    DoSomething();
    DoSomething();



  • no wtf at all. It would be a WTF if it was like that:

    for ($i=0; $i<=10; $i++)  /* a loop from 0 to 1 is pathetic /
    {
       if ($i<=1) /
    need only 0 and 1 */
       {
          ...
       }
    }



  • Yeah this isn't a WTF, I've written code just like that.

    EX:

    Dim hive as Microsoft.Win32.RegistryKey

    For var i = 0 to 1
      If i = 0 Then
        hive = Microsoft.Win32.Registry.LocalMachine
      Else
        hive = Microsoft.Win32.Registry.CurrentUser

      EndIf

      Dim k as Microsoft.Win32.RegistryKey = hive.OpenKey(blah blah blah);
      'etc
      k.Close();
    Next i



  • @The MAZZTer said:

    Yeah this isn't a WTF, I've written code just like that.

    EX:

    Dim hive as Microsoft.Win32.RegistryKey

    For var i = 0 to 1
      If i = 0 Then
        hive = Microsoft.Win32.Registry.LocalMachine
      Else
        hive = Microsoft.Win32.Registry.CurrentUser

      EndIf

      Dim k as Microsoft.Win32.RegistryKey = hive.OpenKey(blah blah blah);
      'etc
      k.Close();
    Next i

    Uhm, thats what subroutines are for...
    function DoStuff(hive)
    Dim k as Microsoft.Win32.RegistryKey = hive.OpenKey(blah blah blah);
      'etc
      k.Close();
    end function

    doStuff(Microsoft.Win32.Registry.LocalMachine)
    doStuff(Microsoft.Win32.Registry.CurrentUser)

    Much cleaner.


Log in to reply