I know incrementing a pointer in this fashion: ptr += 2, involves an addition and multiplication ( 2 * sizeof ptr), whereas doing ptr++ only requires addition.
My assumption was that ptr += 1 would be equivalent to ptr++, however, recently I discovered that ptr += x, where x is always 1 || 0, resets ptr to its starting address when x == 0. This makes me question my original assumption that only addition is involved.
Could it be that because I am using a variable, the compiler treats the code just as if x could contain any other number, which I guess technically it could, and it reverts to my former example or is multiplication always used when employing anything other that postfix increment?
Is there any way to circumvent this, i.e increase a pointer in a manner that is equivalent, instruction wise, to ptr++ while retaining the flexibility of using a variable?
I guess I could pre-compute: size = sizeof ptr and then:
while (x < size)
ptr++;
but I'm not sure if that would be any faster, in fact it could be a lot slower.
And while we are at it, is there a difference, instruction wise, between ptr[x] and (ptr + x).
While typing this, I just realized I could probably get most of my answers by looking at the assembly code generated for the different versions of my code, but I've already written all of this and would still like to get your input.
Thank you guys!