Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is type safety and what are the "type safe" alternatives? [duplicate]

Tags:

c++

c

type-safety

Possible Duplicates:
What is Type-safe?
What is type-safety?

I was reading about c++ vectors and it was mentioned that memcpy and printf functions from C are not type safe. Article here: http://en.wikipedia.org/wiki/Vector_(C%2B%2B).

Question: In simple English, what is type safety and what are the "type safe" alternatives?

like image 598
Dr Deo Avatar asked Jan 26 '10 15:01

Dr Deo


People also ask

What are the types of safety?

In the context of denotational semantics, type safety means that the value of an expression that is well-typed, say with type τ, is a bona fide member of the set corresponding to τ. This formal type-theoretic definition of type safety is considerably stronger than what is understood by most programmers.

What does type of safety mean?

Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable. Some simple examples: // Fails, Trying to put an integer in a string String one = 1; // Also fails.

What is meant by type safety in Java?

A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data. Java is not type-safe, though it was intended to be. A Java object may read and modify fields (and invoke methods) private to another object.

What is type safety and why is it important?

Type safety in the source code is a programming language control that ensures that any variable access only its authorized memory locations in a well-defined and permissible way. In other words, the type safety feature ensures that the code doesn't perform any invalid operation on the underlying object.


2 Answers

Type safety means that the compiler can check whether you're using the right types. For example, if you're using printf, you could accidentally crash your program by writing this:

printf("The meaning of life is %s", 42); 

because 42 is an integer, not a string.

like image 65
Chris Jester-Young Avatar answered Oct 14 '22 03:10

Chris Jester-Young


Type safety means that the compiler will help check that you don't mix (incompatible) data types.

For instance, when you call memcpy, the function (and compiler) only sees two pointers in memory, and will happily start copying data. This means you can mix incompatible data types like this:

SomeClass a; AnotherClass b; memcpy((void*)&a, (void*)&b, sizeof(b)); 

There are many approaches to gaining type safety. You could use templates and make a wrapper around mempcy(), ensuring that the two pointers point to the same data type, or you could use other ways.

Since you are already using vectors from the STL, you are already using a more or less type safe implementation.

like image 23
csl Avatar answered Oct 14 '22 05:10

csl