Comparison Style

Chris Angelico rosuav at gmail.com
Thu Apr 25 22:48:35 EDT 2013


On Fri, Apr 26, 2013 at 12:37 PM, Dennis Lee Bieber
<wlfraed at ix.netcom.com> wrote:
> On Thu, 25 Apr 2013 15:57:49 +1000, Chris Angelico <rosuav at gmail.com>
> declaimed the following in gmane.comp.python.general:
>> It's conventional to compare variables to constants, not constants to
>> variables (even in C where there's the possibility of mucking up the
>> operator, most people still compare variables to constants).
>
>         The main reason for /literal/ first is to trap C/C++ assignment as
> expression.
>
>         if (x = 5)
>
> ends up assigning x the value 5 and THEN, since 5 is "true" executing
> the "then" part.
>
>         if (5 = x)
>
> OTOH is a compiler error.
>

Aware of this. My point is that, even though there's a good reason for
putting the constant first, it's still FAR more common to put the
variable first. Also, this protection helps only when the "constant"
is actually something the compiler knows is a constant - it doesn't
work in a search function, for instance:

char *strchr(char *string, char findme) {
    while (*string) {
        if (*string==findme) return string;
        ++string;
    }
    return 0;
}

If you switch the order of operands in that, the compiler won't help
you. Plus it "reads" wrong. So the convention is still
variable==constant.

ChrisA



More information about the Python-list mailing list