strong/weak typing and pointers

Steven Bethard steven.bethard at gmail.com
Tue Nov 2 18:14:06 CET 2004


Diez B. Roggisch <deets.nospaaam <at> web.de> writes:

> Strong/weak typing is about how much you care of types at all - in php, its
> perfectly legal to add strings to numbers - the string simply gets
> converted to a number beforehand, that conversion yielding 0 when there is
> nothing useful and numberlike can be extracted from the string. So typing
> is weak, as it doesn't constrain the possible operations on variables with
> certain values.

By this definition, Python is also weakly typed:

>>> 2.0 + 1
3.0

Your defintion above calls PHP weakly typed because it performs implicit
string->number conversions.  The Python code above performs an implicit
int->float conversion.

This is not the definition of strongly- and weakly-typed that I'm used to.  When
I use strongly-typed, I mean that a block of memory associated with an object
cannot be reinterpreted as a different type of object.  For example, in a
weakly-typed language like C, we can do:

struct A {
	char c;
	int i;
};
struct B {
	float f;
	char c;
};
int main(int argc, char* argv) {
	struct A a = {'c', 1024};
	struct B* b = (struct B*)&a;
	printf("'%c' %d %f '%c'\n", a.c, a.i, b->f, b->c);
}

And get the following ouptut:
'c' 1024 149611321247666274304.000000 ' '

C allows me to reinterpret a char as a float and an int as a char.  In the first
case, we get the floating-point number that is represented by the bits that
represent the character 'c'.  In the second case, we get the space character
because that's how C prints a character with an ASCII value larger than it's
allowed to be (1024 when the max is 255).

The point here is that I consider C weakly typed because, with no error of any
sort, it allows me to reinterpret a block of memory in as many ways as I like. 
A strongly typed language like Python does not allow this.  Even in my Python
example above, we're not *reinterpreting* the block of memory representing 1 as
a floating point value; we're *coerceing* the integer 1 into the floating point
value 1.0 (which probably means allocating a new float variable at the C level)
before performing the addition.

Steve




More information about the Python-list mailing list