'1' + 1 ==> True ???

Isaac To kkto at csis.hku.hk
Thu Mar 18 09:47:36 EST 2004


>>>>> "Peter" == Peter Maas <fpetermaas at netscape.net> writes:

    Peter> Nicola Mingotti schrieb:
    >> 2) Like C -----> Char is converted to int #include<stdio.h> int
    >> main(){ printf("%i %i", '1' > 1 , '1' + 1 ); return 0;
    >> }

    Peter> That's not really a conversion. '1' is 0x31 in memory and 0x31 >
    Peter> 1.

That's really not a conversion, but not because '1' is 0x31 in memory.  It
is because C defines '1' to be equivalent to (in every respect, including
type) the integer to represent it---which is 49 (0x31) in most computers we
use today.  So in C (and our current platforms), '1' means 49 and 49 means
'1'.  Adding '1' with '1' give you 98, and adding "hello" and '1' gives you
a pointer to the 49-th byte after the beginning of "hello".  The size of '1'
is 4.  C++ is a bit better in the last respect: '1' is of size one byte
rather than 4 bytes in C++ (so in C++ language, char is a short integer).

    Peter> C simply compares memory locations, so comparisons are perhaps
    Peter> even be machine dependent.

Untrue.  It does not try to compare "memory location".  Instead it is simply
comparing based on the values of the two operands.  Since C defines '1' to
be its representational value which is 49, and 49 is greater than 1, the
comparison result is non-zero.

    Peter> Unlike C, Python's comparison results for different types are
    Peter> defined in a strange but archicture independent way, see Python
    Peter> Library Reference 2.3.3.

Also untrue.  Python's comparison result is dependent on implementation, so
even in the same computer, two different Python implementation can give you
different results; and you cannot make any assumption in different
platforms.

Regards,
Isaac.



More information about the Python-list mailing list