int x=1; or int x; x=1;

Feb 14, 2009 at 9:37pm
main()
{
int x=1;
....
int y;
...
...
y=1;
...

I suppose it is nice to be able to immediately see what x is initialized to, (because it is initialized and defined at the same time) instead of looking for the corresponding assignment statement. But other than that, does initialzing x offer any other advantages compared to initializing y ??? I notice in the debugger they both seem to be treated as executable statements, so x is not initialized at compile time, but I would think it should be to improve performance (assuming not just x, but a LOT of integers were being initialized)?
Feb 14, 2009 at 10:06pm
Using int x = 1; should be faster than int x; x=1;
Feb 14, 2009 at 10:11pm
int x=0;
and
1
2
int x;
x=0;

generate the same code. No more and no less.
(Variables are pushed to the stack at the beginning of the function and popped at the end.)
int a=0;
0041138E mov dword ptr [a],0
int b;
b=0;
00411395 mov dword ptr [b],0


Variables don't exist at compile time, so they can't be initialized then. They are pushed onto the stack at run time and initialized (or not) then.
The only way to initialize sufficient integers to make a difference is to put them in an array: int array[a_large_number]={0};
If that array is local, it's initialized every time the function passes that point. If it's global, it's included initialized in the data section of the binary and moved to memory when the program loads, so in that case, the integers are initialized at compile time.

Note that initializing an integer no larger than the biggest register in the CPU takes only 1 clock cycle (for a 2 GHz CPU, that's 0.5 ns).
Last edited on Feb 14, 2009 at 10:19pm
Feb 14, 2009 at 10:26pm
If 'type' isn't a built in type
type x = y;
should differ from
1
2
type x;
x = y;
Feb 14, 2009 at 11:02pm
In that case it does make a difference, because two different constructors are called at different times for version 2.
Feb 15, 2009 at 1:42pm
There is never a reason to make two lines of code to do something that one can do.

 
int x = 1;


is always better than

1
2
int x;
x = 1;


no matter what type you use and what value you assign.

Topic archived. No new replies allowed.