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)
    
    
  • 相关阅读:
    SpringBoot--实现Mybatis的多数据源切换和动态数据源切换
    云服务器查看外网IP地址方法
    Linux性能调优方法总结
    rsyslog配置
    Linux网络优化
    Reversoir sampling
    SQL 中的 NULL 小结
    Go by Example: HTTP Servers
    Linux 在 TOP 命令中切换内存的显示单位
    kubernetes informer 原理解析二
  • 原文地址:https://www.cnblogs.com/keviwu/p/6854009.html
Copyright © 2011-2022 走看看