Saturday, 11 May 2019

c - declare variable inside or outside a loop, does it make big difference?




for example



int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
i = doSomething();
// **


}


and



while(bigNumber--) {
int i, a, b, c; // i'd like to put it here for readability
i = doSomething();
// **
}



Does it make big difference in terms of performance?


Answer



Yes. scope of variable i is different in both cases.



In first case, A variable i declared in a block or function. So, you can access it in the block or function.



In the second case, A variable I declared in a while loop. So, you can access it in while loop only.





Does it make big difference in terms of performance?




No, it will not matter performance-wise where you declare it.



For example 1:



int main()
{

int i, bigNumber;

while(bigNumber--) {
i = 0;
}
}


Assembly:




main:
push rbp
mov rbp, rsp
.L3:
mov eax, DWORD PTR [rbp-4]
lea edx, [rax-1]
mov DWORD PTR [rbp-4], edx
test eax, eax
setne al
test al, al

je .L2
mov DWORD PTR [rbp-8], 0
jmp .L3
.L2:
mov eax, 0
pop rbp
ret


Example 2:




int main()
{
int bigNumber;

while(bigNumber--) {
int i;
i = 0;
}
}



Assembly:



main:
push rbp
mov rbp, rsp
.L3:
mov eax, DWORD PTR [rbp-4]
lea edx, [rax-1]

mov DWORD PTR [rbp-4], edx
test eax, eax
setne al
test al, al
je .L2
mov DWORD PTR [rbp-8], 0
jmp .L3
.L2:
mov eax, 0
pop rbp

ret


Both generate the same assembly code.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...