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)
    
    
  • 相关阅读:
    【转】CSR蓝牙驱动程序引起的Win7奇怪问题
    c# .net WebRequest 始终报域名无法解析
    sql server 安装时提示要重启
    https 不检验证书
    windows 日志,IIS应用程序池回收日志
    excel sum
    .net core 连接sql server 时提示Connection Timeout Expired
    python2.0_day20_bbs系统开发
    SVN常用命令与分支操作
    SVN使用教程之-分支/标记 合并 subeclipse
  • 原文地址:https://www.cnblogs.com/keviwu/p/6854009.html
Copyright © 2011-2022 走看看