Search code examples
language-agnosticprogramming-languagesterminology

Type Safe vs Static Typing?


If a language is type-safe does that mean one could automatically assume that its statically typed since you would have to check types at compile time ?


Solution

  • C, for example, is statically typed and not type safe, while Haskell is statically typed and type safe. Most (all?) dynamically typed languages are type safe, as they have means of checking types at runtime to make sure they're the right thing. Additionally, these languages assume that because you have chosen to incur the performance penalty of including runtime type information, you would want to use that information as effectively as possible, and so generally do not allow interpreting a chunk of memory as the wrong type.

    Dynamically typed languages have an additional measure of type safety, which is coercion. For example, if you type [] + [] in javascript, it will see that the operands to + are arrays and cannot be added directly, and so will convert them both to strings, giving the result of "" (the empty string).

    Some languages, like javascript, will usually coerce other things to strings, while PHP for example will coerce strings to numbers to compare them.

    EDIT: Type safety means not being allowed to interpret a chunk of memory holding something of type A as something of type B. As an example of type unsafety, C++ has the reinterpret_cast operator, which means "convert anything to anything else even if it doesn't make sense to do so." For example,

    float a = 6.2;
    int b = reinterpret_cast<int>(a);
    //b now contains some form of garbage
    

    For a much more complete explanation of type safety, see this answer.