Pointers and Loops

It bothered me a bit for a while: between this

there is a difference (e.g. memory)
Pointer *somePointer; for (...) { somePointer = something; // do stuff with somePointer } 

and this one

 for (...) { Pointer *somePointer = something; // do stuff with somePointer } 
+4
source share
4 answers

Well, firstly, in your second example, somePointer will only be valid inside the loop (its scope), so if you want to use it outside, you need to do as in fragment # 1.
If we enable the assembly, we will see that the second fix requires 2 more instructions:

Fragment 1:

 for(c = 0; c <= 10; c++) (*p1)++; 0x080483c1 <+13>: lea -0x8(%ebp),%eax # eax = &g 0x080483c4 <+16>: mov %eax,-0xc(%ebp) # p1 = g 0x080483c7 <+19>: movl $0x0,-0x4(%ebp) # c = 0 0x080483ce <+26>: jmp 0x80483e1 <main+45> # dive in the loop 0x080483d0 <+28>: mov -0xc(%ebp),%eax # eax = p1 0x080483d3 <+31>: mov (%eax),%eax # eax = *p1 0x080483d5 <+33>: lea 0x1(%eax),%edx # edx = eax + 1 0x080483d8 <+36>: mov -0xc(%ebp),%eax # eax = p1 0x080483db <+39>: mov %edx,(%eax) # *p1 = edx 0x080483dd <+41>: addl $0x1,-0x4(%ebp) # c++ 0x080483e1 <+45>: cmpl $0xa,-0x4(%ebp) # re-loop if needed 0x080483e5 <+49>: jle 0x80483d0 <main+28> 

Fragment 2:

 for(c = 0; c <= 10; c++) { int *p2 = &g; (*p2)--; } 0x080483f0 <+60>: lea -0x8(%ebp),%eax # eax = &g 0x080483f3 <+63>: mov %eax,-0x10(%ebp) # p2 = eax 0x080483f6 <+66>: mov -0x10(%ebp),%eax # eax = p2 0x080483f9 <+69>: mov (%eax),%eax # eax = *p2 0x080483fb <+71>: lea -0x1(%eax),%edx # edx = eax - 1 0x080483fe <+74>: mov -0x10(%ebp),%eax # eax = p2 0x08048401 <+77>: mov %edx,(%eax) # *p2 = edx 0x08048403 <+79>: addl $0x1,-0x4(%ebp) # increment c 0x08048407 <+83>: cmpl $0xa,-0x4(%ebp) # loop if needed 0x0804840b <+87>: jle 0x80483f0 <main+60> 

Well, the difference lies in the first two instructions of fragment No. 2, which are executed in each cycle, and in the first fragment, they are executed immediately before entering the cycle.
I hope I understand.;)

+3
source

If you want to use a pointer when you finish the loop, you need to do the first.

 Pointer *somePointer; Pointer *somePointer2; for(loopA) { if(meetsSomeCriteria(somePointer)) break; } for(loopB) { if(meetsSomeCriteria(somePointer2)) break; } /* do something with the two pointers */ someFunc(somePointer,somePointer2); 
+4
source

Well, with the first version you only need to unlock, after the loop. In the second version, you cannot use a pointer outside the loop, so you need to free it inside the loop. It is clear that this is not so important, but in the second example you have overhead.

0
source

check out a similar answer on stackoverflow here with some good answers. However, it is probably compiler / language independent ...

0
source

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


All Articles