0

Based on what I know about type safety, a type safe language does not allow you to assign a variable of one type to a variable of a different type (unless you perform an explicit conversion). But in C and C++ I can do the following:

int i = 12345;
float f = i;    // this is allowed

Is this operation considered not type safe?

  • It doesn't means any conversion is prohibited. There're still implicit conversions being allowed. – songyuanyao Sep 16 '16 at 05:32
  • This is allowed in C and C++. Use whatever words you like to describe it... – M.M Sep 16 '16 at 05:32
  • 2
    In C++ you can use braces to avoid implicit conversions that might lose precision, e.g. `float f = { i };` – M.M Sep 16 '16 at 05:32
  • Other duplicates & related: [C++ implicit conversions](http://stackoverflow.com/q/867462/514235) ... and ... [Implicit type conversion rules in C++ operators](http://stackoverflow.com/q/5563000/514235) ... and ... [C++ floating point to integer type conversions](http://stackoverflow.com/q/2544394/514235) – iammilind Sep 16 '16 at 05:36
  • yes, it is a violation of type safety for the sake of convenience. – Mike Nakis Sep 16 '16 at 05:40
  • Sure, given that definition of "type safe", C and C++ and Java and a bunch of other languages are not "type safe". – Pete Becker Sep 16 '16 at 12:51

1 Answers1

1

[..] a type safe language does not allow you to assign a variable of one type to a variable of a different type (unless you perform an explicit conversion).

I don't think that this would be a good definition. Rather I'd say that a type safe language does not allow operations specific to / designed for a type X to be performed on a value of a other type Y if those two types are not considered compatible under some metric. That's what's known as strong typing (not to be confused with static typing).

Is this operation considered not type safe?

It's a well defined (albeit implicit) conversion from one type to another.

What seems to be bugging you is the part that this conversion is implicit and not explicit. I don't know of a distinct "term" / word to describe that a language allows implicit conversions, though.

That said, C++ surely is not type safe in all respects.

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63