Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a type safe language needs to be statically typed?

I am trying to understand what it means for a language to be type-safe. In a dynamically typed language, the type checking is performed at run time, so for example if I run the following PHP code:

<?php
class MyClass
{ 
}

// Create a MyClass instance
$mc = new MyClass();

// Create an int variable
$i = 1234;

// Add $mc and $i
$result = $mc + $i;
?>

I will get an error because the + operator does not support the MyClass data type. So basically the type checking was performed at run time.

Does type safety means that type checking is performed regardless if it is performed at compile time or at run time, or does it mean that type checking must be performed only at compile time and so each variable must be given a data type explicitly (like C, Pascal, Java, etc.).


1 Answers

"Type safe" usually means "memory type safe", that is, you can't treat the memory that contains one type as if it was another type.

By this definition, most higher-level languages, including dynamically typed languages, are type safe, because any attempt to use a type incorrectly is guaranteed to cause an error (compile-time or run-time) in them.

So, type safety is mostly an issue for low-level languages, especially C and C++. And those issues often involve pointers or casting (e.g. reinterpret_cast in C++).

C# is an interesting case that lies between the two groups: it is type safe by default, but you can turn off type safety for parts of your code using the unsafe keyword (usually for performance or interop reasons).


But if you combine type safety with static typing, it doesn't necessarily mean having to write types. Many static type-safe languages, especially functional ones, or those inspired by them, use type inference. This means that the compiler can figure out the type of a variable by itself, based on what's assigned to it, so you don't have to type it. Examples of this are the auto keyword in C++ and var in C#.

like image 98
svick Avatar answered Oct 26 '25 17:10

svick