Programming Language for Games, part 3

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Sat Nov 1 18:44:37 PDT 2014


On Sat, Nov 01, 2014 at 05:53:00PM -0700, Walter Bright via Digitalmars-d wrote:
> On 11/1/2014 3:32 PM, bearophile wrote:
> >Paulo Pinto:
[...]
> >>- no implicit type conversions
> >D has a large part of the bad implicit type conversions of C.
> 
> D has removed implicit conversions that result in data loss. Removing
> the rest would force programs to use casting instead, which is far
> worse.
[...]

While D has removed *some* of the most egregious implicit conversions in
C/C++, there's still room for improvement.

For example, D still has implicit conversion between signed and unsigned
types, which is a source of bugs. I argue that using casts to convert
between signed and unsigned is a good thing, because it highlights the
fact that things might go wrong, whereas right now, the compiler happily
accepts probably-wrong code like this:

	uint x;
	int y = -1;
	x = y;	// accepted with no error

D also allows direct assignment of non-character types to character
types and vice versa, which is another source of bugs:

	int x = -1;
	dchar c = x; // accepted with no error

Again, requiring the use of a cast in this case is a good thing. It
highlights an operation that may potentially produce wrong or unexpected
results. It also self-documents the intent of the code, rather than
leaving it as a trap for the unwary.

On the other hand, D autopromotes arithmetic expressions involving
sub-int quantities to int, thus requiring ugly casts everywhere such
arithmetic is employed:

	byte a, b;
	a = b - a;	// Error: cannot implicitly convert expression (cast(int)b - cast(int)a) of type int to byte

You are forced to write this instead:

	byte a, b;
	a = cast(byte)(b - a);

I know the rationale is to prevent inadvertent overflow of byte values,
but if we're going to be so paranoid about correctness, why not also
require explicit casts for conversion between signed/unsigned, or
between character and non-character values, which are just as
error-prone? Besides, expressions like (b-a) can overflow for int values
too, yet the compiler happily accepts them rather than promoting to long
and requiring casts.


T

-- 
What do you mean the Internet isn't filled with subliminal messages? What about all those buttons marked "submit"??


More information about the Digitalmars-d mailing list