Undefined behaviours in D and C

Walter Bright newshound1 at digitalmars.com
Sun Apr 18 20:28:40 PDT 2010


bearophile wrote:
> The first of them is fixed in C99 with the 'restrict' keyword. I
> guess the D compiler has to assume all pointers can be an alias to
> each other (but I don't remember if the D docs say this explicitely
> somewhere) because I think D prefers to not give keywords that the
> compiler itself can't then test and make sure they are correct.

'restrict' is not at all about eliminating undefined behavior. It is 
about providing more information to the optimizer so better code can be 
generated. If restrict is used incorrectly, however, undefined behavior 
can result. D doesn't have this problem because D doesn't have the 
restrict qualifier.

> The second of them is relative to code like:
> 
> enum SI { short s; int i; } void main() { SI e; e.i = 1_000_000; int
> foo = e.s; }
> 
> I think that according the C standard this code (the contents of foo)
> is undefined. Is D going to define this, or is it going to leave this
> undefined as in C? (Leaving it undefined can speed up a little the D
> code, but making it defined can make D more flexible, for example you
> can use an enum to split an int in two shorts in a reliable way).
> Note: here I am talking about D unsafe modules, because I think safe
> D modules can't use enums. So I am talking about the possibility of
> removing some undefined behaviours from unsafe D modules.

D leaves byte ordering (endianness) implementation defined. I see no way 
to do otherwise without incurring severe performance penalties.

> Probably the C standard leaves other things undefined. Some of them
> can cause bugs in unsafe D code.

Yes, endianness issues can cause bugs.



More information about the Digitalmars-d mailing list