Basic question about size_t and ulong

Ali Çehreli acehreli at
Tue Mar 22 18:47:19 UTC 2022

On 3/22/22 11:28, Era Scarecrow wrote:

 >   So when should you use size_t?

I use size_t for anything that is related to count, index, etc. However, 
this is a contested topic because size_t is unsigned. As soon as you use 
it in an expression, the whole expression becomes unsigned as well. 
(Related: Usual Arithmetic Conversions at the link below.)

For that reason, at least during an "ask us anything" session at a C++ 
conference, where Andrei was among the panel, Herb Sutter and others 
agreed that it was a mistake to choose unsigned for size_t.

So far, I didn't have much trouble from that decision. I am always 
careful when subtracting two size_ts.

 > Is it better to use int, long, size_t?

D uses size_t for automatic indexes during foreach, and as I said, it 
makes sense to me.

Otherwise, I think the go-to type should be int for small values. long, 
if we know it won't fit in an int.

 > Or is it better to try to use the smallest type you need that will
 > fulfill the function's needs and just add to handle issues due to
 > downcasting?

That may be annoying, misleading, or error-prone because smaller types 
are converted at least to int in expressions anyway:

(Every D programmer should know the whole section 6.4 there.)

But yeah, if your function works on a byte, sure, it should take a byte.

Expect wild disagreements on this whole topic. :)


More information about the Digitalmars-d-learn mailing list