Defending the ternary operator

Andrew Koenig ark at research.att.com
Sat Feb 8 13:13:56 EST 2003


David> In article <yu99k7gaagav.fsf at europa.research.att.com>,
David>  Andrew Koenig <ark at research.att.com> wrote:

>> EXAMPLE 6:
>> 
>> p = (s == NULL)? str: s;
>> 
>> This example sets a default value to substitute for s in case s is NULL.
>> The likely rewrite:
>> 
>> if (s == NULL)
>>    p = str;
>> else
>>    p = s;

David> What's wrong with using s || str in this example?

Different semantics.  Writing

        p = s || str;

would be the same as

        if (s == NULL) {
           if (str == NULL)
                p = 0;
           else
                p = 1;
        }

which, in turn, wouldn't compile because you can't assign 1 to a pointer.

Perhaps you were thinking that "||" in C works like "or" in Python?
        
-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark




More information about the Python-list mailing list