Tomás posted:
>
> Is the following fully legal and fully portable for all the unsigned
> types? The aim of the function is to take an array by reference and set
> each element's value to zero.
>
> #include <...
>
> template<class UnsignedNumericType, std::size_t const i>
> void SetAllElementsToZero( UnsignedNumericType (&array)[i] )
> {
> memset( array, 0, i * sizeof(UnsignedNumericType) );
>
> //or:
>
> memset( array, 0, sizeof (array) );
> }
>
>
> I writing a function at the moment that's manipulating an array which
is
> passed to it by reference. It needs to set a certain amount of the
> elements to zero. It will only ever be given the unsigned types, e.g.:
>
> unsigned
> unsigned char
> unsigned short
> unsigned long...
>
>
> Is the code fully portable and well defined? Is there a guarantee in
the
> Standard that the bit pattern in memory for all the aforementioned
types
> will be all zeros, ie. 0000 0000?
>
>
> -Tomás
Anywho, what got me thinking of this is how you can't use this method
with pointers. For instance, take :
1) int* p = 0;
2) int* p;
memset(p,0,sizeof(int*) );
The 1st method sets the pointer to a "null pointer", which may or may not
represent "all bits zero" in memory.
The 2nd methos sets the pointer to "all bits zero" in memory, which may
or may not represent "all bits zero" in memory.
Actually come to think of it, if we've no guarantee that an unsigned
numeric type stores its zero value as "all bits zero", then we've not
guarantee that when we pass a zero literal (ie. 0) to memset, that it
will make the memory all bits zero...
-Tomás
|