Some quick questions

Chris Nicholson-Sauls ibisbasenji at gmail.com
Tue Aug 7 13:22:23 PDT 2007


Márcio Faustino wrote:
> Hi, I have some quick questions:
> 
> (1.) Why does version 2.0 of the compiler doesn't allow changing the 
> index of a foreach loop? For example:
> 
> ;string format = "%s";
> ;
> ;foreach (i, c; format) {
> ;    if (c != '%') {
> ;        // ...
> ;        continue;
> ;    }
> ;   
> ;    switch (format[++i]) {
> ;    case 's':
> ;        // ...
> ;        break;
> ;    // ...
> ;    }
> ;}
> 
> Instead of the (more tedious):
> 
> ;string format = "%s";
> ;bool was_escape = false;
> ;
> ;foreach (i, c; format) {
> ;    if (was_escape) {
> ;        was_escape = false;
> ;        continue;
> ;    }
> ;    if (c != '%') {
> ;        // ...
> ;        continue;
> ;    }
> ;   
> ;    was_escape = true;
> ;    switch (format[++i]) {
> ;    case 's':
> ;        // ...
> ;        break;
> ;    // ...
> ;    }
> ;}

I remember there being a reason... darned if I recall it exactly, 
though.  And actually I think the reasoning had mainly to do with inout 
indices, as changing them potentially leads to undefined behavior. 
(Just like modifying an array while foreach'ing over it is a problem.) 
Times like this I wish there was a 'skip' command for loops, or at least 
some reasonable allowances.

> 
> (2.) What's the rationale for opEquals returning an int, given that we 
> have a bool data type? (And it clearly returns a boolean value.)

Historical reasons.  Although, you actually /can/ define it as returning 
bool and nothing will break -- D's bool and int types are the same under 
the hood, and implicitly cast.

> (3.) Shouldn't the toHash method of the Object class return 
> "cast(hash_t) cast(void*) this" instead of "cast(uint) cast(void*) 
> this", since the hash_t type is defined differently for x86 and x64?

Yes.  Yes it should.  :)

> (4.) Shouldn't the equals method of the TypeInfo_i class use casts to 
> int's instead of uint's, since that TypeInfo class is for int's?

Possibly.  Unless there's some tiny gain in casting to an unsigned type 
over a signed?  (I really doubt it.)

-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list