Type Systems – Difference Between Casting and Converting Types in Imperative Languages

conceptsimperative-languagestype castingtype-systemsweak-typing

The question came up in a discussion at StackOverflow.

Is there a clean distinction between the two concepts cast and convert (concerning the type of an object), or are these two words describing exactly the same? How about languages other than C++, Python and Java? EDIT: What if the types in question are primitive types, like int to float?

Best Answer

Theoretically speaking, the two concepts are vastly different:

Type Casting refers to exchanging one type (roughly speaking, an object structure) for another while Type Conversion refers to translating of values (roughly speaking, contents of the object), so that they may be interpreted as belonging to a new type. Theoretically, they never mix.

That said, practically speaking, while you can have one without another, it's, almost always, a bad idea. It rarely makes sense to change your perception of an objects' structure, without also altering its contents. Practically, they're almost always the same

Related Topic