www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - int or size_t ?

reply %u <asmasm hotmail.com> writes:
In Patterns of Human Error, the slide 31 point that you should replce int with
size_t
why that consider an error ?
May 07 2011
next sibling parent reply bearophile <bearophileHUGS lycos.com> writes:
%u:

 In Patterns of Human Error, the slide 31 point that you should replce int with
 size_t
 why that consider an error ?

If T is a byte and the array size is 5 billion items, on 64 bit systems...? In the little find() function you compare it with the length, that's a size_t. Someone else will give you better answers. Bye, bearophile
May 07 2011
next sibling parent %u <asmasm hotmail.com> writes:
size_t val1 = int.max+1;
int val2 = int.max+1;
writeln(val1); // 2147483648
writeln(val2); // -2147483648

very clear example

thanks you both
May 07 2011
prev sibling next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Actually my example was bad. What I wanted to say is that size_t will
be 64bit on 64bit platforms while int will stay 32bit. Another
difference is that size_t is unsigned. So it's bad to use int even if
you're sure you're only going to compile only on 32bit platforms.

Here's the relevant definitions in object_.d:

version(X86_64)
{
    alias ulong size_t;
    alias long  ptrdiff_t;
    alias long  sizediff_t;
}
else
{
    alias uint  size_t;
    alias int   ptrdiff_t;
    alias int   sizediff_t;
}

And an example:
void main()
{
    size_t val = size_t.max;    // maximum unsigned 32bit number on
32bit platforms

    int val2 = val;
    writeln(val2);              // -1 on 32bit platforms, due to
unsigned -> signed conversion
}

Usually people type "int" because.. well it's used everywhere and it's
easy to type. I never liked the "size_t" name, but it has become a de
facto standard in other languages, so D uses that name as well. We've
already had a discussion on changing its name but nothing came out of
it.
May 07 2011
prev sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Edit: I just saw you've already figured this out. :)
May 07 2011
prev sibling next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
void main()
{
    size_t val = int.max+1;
    int val2 = val;
    writeln(val2);
}

writes -2147483648

That should give you a hint.
May 07 2011
prev sibling parent Stewart Gordon <smjg_1998 yahoo.com> writes:
On 07/05/2011 18:09, %u wrote:
 In Patterns of Human Error, the slide 31 point that you should replce int with
 size_t
 why that consider an error ?

For those who aren't sure what this is on about: http://www.slideshare.net/dcacm/patterns-of-human-error But the short answer is because dim is a size_t, i needs to cover its range. But.... <= should be = ? Don't you mean < ? And the use of a meaningless type alias gets at me. Stewart.
May 08 2011