Compiler says cast then when done says no can do

Steven Schveighoffer schveiguy at yahoo.com
Tue May 27 09:53:12 PDT 2008


"Ty Tower" wrote
>I have this line
>
> double balance=values[6]-values[5]; (values 5&6 are char[])
>
> so I change to
> double balance=-(double)values[6]-(double)values[5];
> compiler says : C style cast illegal, use cast(double)values[6]
>
> so I change to
> double balance=cast(double)values[6]-cast(double)values[5];
> compiler says: Error: e2ir: cannot cast from char[] to double
>
> So as I see it the compiler message in this case at least is wrong or 
> there is a problem casting from a char array to a double . Is it a problem 
> with the compiler message?

The error might be in the order of operations.  I think the compiler is 
casting your variable, then applying the index operation.  So if you add the 
appropriate parentheses for default order of precedence, it looks like:

(cast(double)values)[6] ...

So what you really want is:

cast(double)(values[6]) - cast(double)(values[5]);

or what might be simpler:

cast(double)(values[6] - values[5]);

to force the order of operations.

I have no idea what the proper order of operations is, so this all might be 
BS, but it's almost impossible to determine the correct order for normal 
people (i.e. people who don't write/read grammar expressions regularly). 
However, the order of operations is sort of built into the grammar on 
http://www.digitalmars.com/d/2.0/expression.html

What makes sense to me is the index operator should be applied before the 
cast, but apparently that's not the case here...

-Steve 




More information about the Digitalmars-d-learn mailing list