Is there a difference between initializing a variable and assigning it a value immediately after declaration?

前端 未结 4 1246
孤街浪徒
孤街浪徒 2020-12-19 21:05

Assuming a purely non-optimizing compiler, is there any difference in machine code between initializing a variable and assigning it a value after declaration?

4条回答
  •  余生分开走
    2020-12-19 21:33

    int x = 2;
    

    Computer will create variable x and assign to it value 2 almost at the same moment.


    int x;
    x = 2;
    

    Computer will create variable x. And then it will it assigned to it value 2. It seem that there is no any difference, but...

    ...let's suppose that your code is like this:

    int x; 
    {some operators};
    x = 2; 
    

    computer may have to access the variable x in order to assign to it value 2. It means that while running program computer will spend more time to access x to assing to it some value unlike if it will create variable and assing this variable at the moment.

    Anyway, Deitel HM, Deitel PJ describe this in C How to Program.

提交回复
热议问题