zoukankan      html  css  js  c++  java
  • 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)
    
    
  • 相关阅读:
    矩阵距离
    CF409D Big Data
    AT2685 i18n
    P3366 【模板】最小生成树
    P3367 【模板】并查集
    ISBN(洛谷P1055)
    关于数组
    0021---一元一次方程
    0020---求圆锥体积
    0019---求圆台的体积
  • 原文地址:https://www.cnblogs.com/keviwu/p/6854009.html
Copyright © 2011-2022 走看看