C++ should define all local variable outside the loop?

see the following two examples, the conclusion is that we should define variable in the loop if it can.

//test1.cc outside the loop
#include<stdio.h>

int main()
{
    int tmp = 0;
    for (int i = 0; i < 64; ++i) {
        tmp = i;
    }   

    return 0;
}

//test2.cc inside the loop
#include<stdio.h>

int main()
{
    for (int i = 0; i < 64; ++i) {
        int tmp = i;
    }

    return 0;
}

The assembly code:

;test1.s
    .file   "test1.cc"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16 
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $0, -4(%rbp)
    movl    $0, -8(%rbp)
.L3:
    cmpl    $63, -8(%rbp)
    jg  .L2 
    movl    -8(%rbp), %eax
    movl    %eax, -4(%rbp)
    addl    $1, -8(%rbp)
    jmp .L3 
.L2:
    movl    $0, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005"
    .section    .note.GNU-stack,"",@progbits



;test2.s
    .file   "test2.cc"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16 
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $0, -8(%rbp)
.L3:
    cmpl    $63, -8(%rbp)
    jg  .L2 
    movl    -8(%rbp), %eax
    movl    %eax, -4(%rbp)
    addl    $1, -8(%rbp)
    jmp .L3 
.L2:
    movl    $0, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005"
    .section    .note.GNU-stack,"",@progbits


difference of assembly code:

$ diff test1.s test2.s
1c1
< 	.file	"test1.cc"
---
> 	.file	"test2.cc"
13d12
< 	movl	$0, -4(%rbp)

原文地址:https://www.cnblogs.com/keviwu/p/6854009.html