www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Implicit conversion error

reply "Paul" <paul example.com> writes:
When compiled on a 64 bit machine, this line

int r = uniform(0, mobs.length);

gives me an error:
Error: cannot implicitly convert expression (uniform(0, 
mobs.length)) of type ulong to int

but it compiles ok on a 32 bit machine.

I thought it was the expression on the righthand side returning a 
ulong which won't 'fit' in an int but if I substitute a numerical 
value instead of trying to get the length, eg uniform(0, 5) it 
compiles.

Why is that?

(mobs is an array of structs)

TIA

Paul
Apr 30 2015
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Paul:

 When compiled on a 64 bit machine, this line

 int r = uniform(0, mobs.length);
".length" returns a size_t, and 0 is an int. uniform() probably decides to unify those types to a size_t. A size_t is 32 bit on 32 bit machines and 64 bits on 64 bit machines. But D "int" is always a 32 bit signed integer. D allows implicit assignment of a 32 bit size_t to int but not a 64 bit size_t to an int. I agree that it's a bit of a mess. Bye, bearophile
Apr 30 2015
parent "Paul" <paul example.com> writes:
On Thursday, 30 April 2015 at 22:24:15 UTC, bearophile wrote:
 Paul:

 When compiled on a 64 bit machine, this line

 int r = uniform(0, mobs.length);
".length" returns a size_t, and 0 is an int. uniform() probably decides to unify those types to a size_t. A size_t is 32 bit on 32 bit machines and 64 bits on 64 bit machines. But D "int" is always a 32 bit signed integer. D allows implicit assignment of a 32 bit size_t to int but not a 64 bit size_t to an int. I agree that it's a bit of a mess. Bye, bearophile
Thank you for the explanation, it makes perfect sense despite being a bit of a surprise. (I should have worked this out for myself but I haven't figured out how to use the documentation properly yet!). Paul
May 01 2015