2 == '2abcdefg'

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I was just wondering why

2 == '2abcdefg'

Evaluates to true?  Is there a reasoning behind this?


Re: 2 == '2abcdefg'

In our last episode,
lovely and talented Doug broadcast on comp.lang.php:

Quoted text here. Click to load it

Well there is a rule behind it.  The rule for converting strings to numbers
is that from the left the string is interpreted as a number so far as it is
a possible number.  When the first character that cannot be part of a number
is encountered, conversion stops and the rest of the string, if any is
ignored.  If the first character cannot be part of a number or if the string
is empty, the value is 0.


2 == '2e10fg' evaluates as false because 2e10 is a possible number, namely
the float 2e10; but

2 == '2f10eg' evaluates as true because f cannot be part of a number so
conversion of the string to a number stops.

It is reasonably convenient at times that 2 == '2'.  I am not so sure
that 11 == '10 pigs' + 1 is convenient so often, but it is there if you
want it.

        Lars Eighner <http://larseighner.com/ usenet@larseighner.com
            82 days since Rick Warren prayed over Bush's third term.
   Obama: No hope, no change, more of the same. Yes, he can, but no, he won't.

Re: 2 == '2abcdefg'

Doug wrote:

Quoted text here. Click to load it

Yeah, and it's called "implicit variable type casting". The above expression
gets implicitly converted into:

2 == (int) '2abcdefg'

And, when run, (int) '2abcdefg' evaluates to 2.

You should RTFM on type casting and type juggling, as this stuff is nicely
covered there.

Iván Sánchez Ortega -ivan-algarroba-sanchezortega-punto-es-

Q:      How many journalists does it take to screw in a light bulb?
A:      Three.  One to report it as an inspired government program to bring
        light to the people, one to report it as a diabolical government plot
        to deprive the poor of darkness, and one to win a Pulitzer prize for
        reporting that Electric Company hired a light bulb-assassin to break
        the bulb in the first place.

Re: 2 == '2abcdefg'

Iv=C3=A1n S=C3=A1nchez Ortega wrote:
Quoted text here. Click to load it

And its one of the things that gives people who are used to properly=20
typed languages hell.

Its the same in javascript. Although the rules for typing are well laid=20
out, they do not cover every case  and there are plenty of holes through =

which you can slip.

Site Timeline