Search code examples
c++performancehpc

Is there any difference between (ptr + i)->Func() and &ptr[i].Func()


Or both of them are equal? ptr is a pointer to an array of structs.

UPD: Thank you all for the response. I'm sorry, I misspelled the syntax. What I'm trying to compare is (ptr + i)->Func() vs (&ptr[i])->Func(). I'm confused with a & operator as it is supposed to return address of a variable. Doesn't it result into one more operation of taking that address?


Solution

  • You probably mean &ptr[i]->Func(), otherwise your expressions do not have identical functionality.

    According to C++ standard, adding a value of pointer type to a value of integral type produces a pointer of the same type as original at the offset equal to the value of integral type. The same value is produced by taking an address of ptr[offset], so the two are identical. Moreover, the order of addition does not matter, so all of the expressions below do the same thing, and should produce identical executable codes:

    &ptr[i]
    (ptr+i)
    (i+ptr)
    &(i[ptr]) // <<== Don't do this!
    

    The last item is there only as a curiosity. Do not use this construct in code outside of programming puzzles.