Are address offsets allowed during compilation in C / C ++?

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 eliminating manual bias at compile time or adds overhead to perform arithmetic operations at runtime?

-1
source share
2 answers

Even if you have a constant instead of sizeof(int) , the compiler cannot know the address in p beforehand, so it will have to make an addition. If you have something like i = sizeof(int)+4 , then it should execute compile time with optimizations and directly set i to 8 .

Also, I think when you do this:

 *((int*)p+sizeof(int)) = 777; 

what do you mean:

 *((int*)p + 1) = 777; /* or ((int*)p)[1] = 777; */ 

Similar to printf("%d ", *((int*)p+sizeof(int)*i)); should be:

 printf("%d ", *((int*)p + i)); 
+3
source

sizeof(int) definitely known at compile time, and it makes sense to use this information effectively. However, there is no guarantee that this compiler will generate something like this:

 mov dword [ebx+16], 777 

instead of the following:

 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 
+2
source

Source: https://habr.com/ru/post/920535/


All Articles