Re: c99/c++ localised variable definition

From: Paul Richards (paul_at_originative.co.uk)
Date: 02/01/05

  • Next message: Marcel Moolenaar: "Re: c99/c++ localised variable definition"
    Date: Tue, 1 Feb 2005 20:43:31 +0000
    To: Marcel Moolenaar <marcel@xcllnt.net>
    
    

    On Tue, Feb 01, 2005 at 12:30:37PM -0800, Marcel Moolenaar wrote:
    > On Feb 1, 2005, at 11:04 AM, Paul Richards wrote:
    >
    > >>And wonder why i gets such a strange value... It appears that unless
    > >>you have WARNS=4 set, warnings about:
    > >>t.c:10: warning: declaration of 'i' shadows a previous local
    > >>
    > >>don't show up. So, I would say we HAVE to get the tree building with
    > >>WARNS=4 and -Werror before we let this into style(9)...
    > >
    > >The issue with shadowing outer scope variables is only an issue if
    > >you need to access them. If your only using the syntax for loop
    > >variables to do the looping then there's no issue.
    >
    > Never forget that you want to be able to debug you application.
    > While technically you're right, it's bad practice to do so.

    I disagree with this point. I think it's more error prone to rely on a
    side effect of a loop variable to exist outside the scope of the loop.
    I know that C programmers are used to this, but from the perspective
    of good programming practice I don't think it's a good one.

    Of these two situations:

    Case 1:

    int i;

    for (i = 0; i < MAX; i++)
            if (i == 5) break;

    printf("Found %dth element\n");

    Case 2:

    int fifth_element = 0;

    for (int i = 0; i < MAX; i++)
            if (i == 5) {
                    fifth_element = i;
                    break;
            }
    }

    if (fifth_element)
            printf("Found %dth element", fifth_elemtn);

    The latter seems the better written code to me. It's more verbose, but
    it's clearer what's being done. It seems pointless when you consider
    it in isolation but since probably more than 99% of for loops only
    declare outer scope variables in order to terminate the loop the above
    is the exception and not the rule and for the other 99% of the time
    using localised looping variables is better since it doesn't pollute
    the outer scope.

    -- 
    Paul Richards
    _______________________________________________
    freebsd-arch@freebsd.org mailing list
    http://lists.freebsd.org/mailman/listinfo/freebsd-arch
    To unsubscribe, send any mail to "freebsd-arch-unsubscribe@freebsd.org"
    

  • Next message: Marcel Moolenaar: "Re: c99/c++ localised variable definition"