cvariablesinitialization

Is there some performance difference with these types of variable initialization?


In a local scope (like a function), given these 4 examples:

(1)

int x;
int y;
// code...
x = 4;
y = 5;

(2)

int x = 4;
int y = 5;
// code...

(3)

// code...
int x = 4;
// code...
int y = 5;

(4)

// any other possibility

There is some performance difference in the form I declare and initiate my variables, Or compile take track of that for me?

Edit

I'm asking because I have read often that its better to put all declarations at the most first lines that would be better for performance. Like:

func(){
    int x,y,z,w;
    long bla,ble;
    MYTYPE weeee;
    // more declarations..
    //code..
}

But I didnt know why.


Solution

  • I'm asking because I have read often that its better to put all declarations at the most first lines that would be better for performance.

    I can ensure you that this is pure nonsense. People making such statements have no idea whatsoever how C code is translated into machine code.

    I would be very surprised if any of your 3 examples gave different machine code.


    However there exists a special case: had the variables been declared as "globals" or static, then they would have static storage duration. And then they would be initialized before main() is called. All globals/statics that aren't explicitly initialized by the programmer, are set to zero. So in that case, your example 1) would have been slower:

    int x; /* global variable, no explicit init so it will get set to 
              zero before main() is called */
    ...
    x = 4; // variable gets set a second time, elsewhere, in "runtime"
    

    is slower than

    int x = 4; // global variable, gets initialized before main() is called
    

    The performance difference between these two is however likely just one CPU instruction, so in 99.9% of all applications it won't matter.