Difference between declaring variables before or in loop?

前端 未结 25 2460
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 03:24

    A) is a safe bet than B).........Imagine if you are initializing structure in loop rather than 'int' or 'float' then what?

    like

    typedef struct loop_example{
    
    JXTZ hi; // where JXTZ could be another type...say closed source lib 
             // you include in Makefile
    
    }loop_example_struct;
    
    //then....
    
    int j = 0; // declare here or face c99 error if in loop - depends on compiler setting
    
    for ( ;j++; )
    {
       loop_example loop_object; // guess the result in memory heap?
    }
    

    You are certainly bound to face problems with memory leaks!. Hence I believe 'A' is safer bet while 'B' is vulnerable to memory accumulation esp working close source libraries.You can check usinng 'Valgrind' Tool on Linux specifically sub tool 'Helgrind'.

提交回复
热议问题