Re: [PATCH] use ptrdiff_t instead of casting int magicks

From: Alex Rousskov <rousskov_at_measurement-factory.com>
Date: Tue, 07 Sep 2010 01:54:25 -0600

On 09/06/2010 04:25 PM, Amos Jeffries wrote:
> On Mon, 06 Sep 2010 09:41:15 -0600, Alex Rousskov
> <rousskov_at_measurement-factory.com> wrote:
>> On 09/06/2010 01:15 AM, Amos Jeffries wrote:
>>> Inspired from the SuSE patch submitted by Christian. This is what I
>>> think should be happening with real ptr maths instead of obsolete
>>> integer math with potential rounding and endian errors.
>>
>>
>>> void
>>> memNodeWriteComplete(void* d)
>>> {
>>> mem_node* n = (mem_node*)(d - _mem_node_data_offset);
>>
>> GCC: pointer of type void * used in arithmetic
>>
>>
>> The value of a (pointer + n) expression depends on what pointer is
>> pointing to. If you want byte-size increments, you have to cast to char*
>
>> or similar.
>
> Meh, one cast too many.
>
>>
>> Using ptrdiff_t instead of int is the right thing to do. I do not thing
>> you need to cast to it in makeMemNodeDataOffset. You may clarify the
>> intent by writing:
>>
>> // calculate data member offset; p is not dereferenced here
>> mem_node *p = 0;
>> return reinterpret_cast<char*>(&p->data) - reinterpret_cast<char*>(p);
>
> The point of using ptrdiff_t with p==0L is to reduce multiple casting to
> non-pointer types.

Sorry, I do not understand what you mean. You have to use char* pointers
for the pointer difference to compile and for the value to be correct.

I am _for_ using ptrdiff_t to store that value. I was just pointing out
that you do not have to explicitly cast to it.

Writing reinterpret_cast<char*>() is the same as writing (char*)(). Just
slightly safer when types change and more search-friendly.

Hope this clarifies,

Alex.
Received on Tue Sep 07 2010 - 07:54:42 MDT

This archive was generated by hypermail 2.2.0 : Tue Sep 07 2010 - 12:00:04 MDT