C language: Is there any difference at the assembly level between the variables in the for loop declared outside and inside?

! ! ! Friends who like to watch videos please click here! ! !

1. Variables are declared outside the for loop

The C code is as follows:

#include <stdio.h>
int main() {
    
    
  int i, p;
  for (i = 0; i < 5; ++i) {
    
    
    p = i;
    printf("%d ", p);
  }
  return 0;
}

The corresponding assembly code is as follows:

mov    DWORD PTR [rbp-0x4],0x0
jmp    0x401581 <main+49>
mov    eax,DWORD PTR [rbp-0x4]
mov    DWORD PTR [rbp-0x8],eax
mov    eax,DWORD PTR [rbp-0x8]
mov    edx,eax
lea    rcx,[rip+0x2a88]        # 0x404000
call   0x402aa0 <printf>
add    DWORD PTR [rbp-0x4],0x1
cmp    DWORD PTR [rbp-0x4],0x4
jle    0x401566 <main+22>
mov    eax,0x0
add    rsp,0x30
pop    rbp
ret    

Second, the variable declaration in the for loop

The C code is as follows:

#include <stdio.h>
int main() {
    
    
  for (int i = 0; i < 5; ++i) {
    
    
    int p = i;
    printf("%d ", p);
  }
  return 0;
}

The corresponding assembly code is as follows:

mov    DWORD PTR [rbp-0x4],0x0
jmp    0x401581 <main+49>
mov    eax,DWORD PTR [rbp-0x4]
mov    DWORD PTR [rbp-0x8],eax
mov    eax,DWORD PTR [rbp-0x8]
mov    edx,eax
lea    rcx,[rip+0x2a88]        # 0x404000
call   0x402aa0 <printf>
add    DWORD PTR [rbp-0x4],0x1
cmp    DWORD PTR [rbp-0x4],0x4
jle    0x401566 <main+22>
mov    eax,0x0
add    rsp,0x30
pop    rbp
ret    

3. Conclusion

The assembly code corresponding to the two pieces of C code is exactly the same, there is no difference.
Therefore, it is recommended to declare variables in the closest place to use.
insert image description here

4. Supplement

The early C language codes were all written under the C90 standard. Variables are not allowed to be declared inside the for loop, but must be declared outside. Over time, everyone formed a habit.
Starting from gcc5.1 released in 2015, the default C language standard is already C11 , so you can safely and boldly use the C99 standard in the future, that is, declare variables in the for loop.


end of text

Guess you like

Origin blog.csdn.net/h837087787/article/details/122143297