Are address offsets resolved during compile time in C/C++? [closed]
Pregunta
void *p = malloc(1000);
*((int*)p) = 666;
*((int*)p+sizeof(int)) = 777;
int i;
for (i = 0; i<10; ++i)
printf("%d ", *((int*)p+sizeof(int)*i));
Is the manual offset being resolved at compile time or does it add overhead of performing arithmetic operations during runtime?
Solución
Even if you have a constant instead of sizeof(int)
, compiler cannot know in advance the address in p
, so it will have to do the addition. If you have something like i = sizeof(int)+4
then it should do the optimization compile time and directly set i
to 8
.
Also, I think when you do:
*((int*)p+sizeof(int)) = 777;
what you mean is:
*((int*)p + 1) = 777; /* or ((int*)p)[1] = 777; */
similarly printf("%d ", *((int*)p+sizeof(int)*i));
should be:
printf("%d ", *((int*)p + i));
Otros consejos
sizeof(int)
is definitely known at compile time and it makes all sense to make efficient use of this information. There's no guarantee, however, that a given compiler will generate something like this:
mov dword [ebx+16], 777
instead of something like this:
mov ecx, 16
mov dword [ebx+ecx], 777
or
lea ebx, [ebx+16]
mov dword [ebx], 777
or even
add ebx, 16
mov dword [ebx], 777