views:

96

answers:

3

I have a few global vars I need to set the value to, should I set it into the main/winmain function? or should I set it the first time I use each var?

+4  A: 

Instead, how about not using global variables at all?

Pass the variables as function parameters to the functions that need them, or store pointers or references to them as members of classes that use them.

James McNellis
I would need to call the function everytime right? or at least for every class that use it?
extintor
@extintor: If you are getting the value for the variable from a function, then you can call that function once, store its result, and pass that result to any function or class that needs it.
James McNellis
+1  A: 

Is there a chance that you won't be using the global var? Is calculating any of them expensive? If so then you have a argument for lazy initialization. If they are quick to calculate or always going to be used then init them on startup. There is no reason not to, and you will save yourself the head ache of having to check for initialization every time you use it.

stonemetal
The main var is the windows version and build numbers, I don't think its expensive to calculate. I am still debating between setting them on startup or calling the functions everytime for each class. Both ways will work just fine I think, but I am a c++ newbie and I still dont know the best practices.
extintor
Then I would follow James' advice and not use globals.
stonemetal
A: 

When the linker links your program together, global variables (also known as writable static data) are assigned to their own section of memory (the ELF .data section) and have a value pre-assigned to them. This will mean that the compiler will not need to generate instructions to initialize them. If you initialize them in the main function, the compiler will generate initialization instructions unless it is clever enough to optimize them out.

This is certainly true for ELF file formats, I am not sure about other executable formats.

doron