rubixibuc rubixibuc - 1 year ago 80
C++ Question

what can you initialize global variables to in c++

Can you initialize global variables in c++, and if possible, what values are allowed?

Answer Source

Yes, of course you can initialize globals. For built-in types, you can use any value you could use for assignment (and you can also initialize arrays, which you can't assign). For a class type, it's up to you to decide what types/values will be allowed (and/or required) when you design the class. For a pre-defined class, you basically have to consult the documentation to figure out what it allows/requires.

Ultimately, however, the fact that it's a global doesn't affect the values that can be supplied. Being a global can affect how you can get the value though--in particular, you obviously can't use values that aren't available yet when that initialization is done. This can be a bit more subtle than it initially seems because very little is guaranteed about the order in which global variables are initialized compared to each other, so (for example) when the constructor for your global variable executes, std::cin, std::cout and std::cerr may not have been constructed yet, so if you want to initialize something based on input from the user, you may have to take special steps to either ensure the order of initialization or else (for example) use C-style I/O for that particular job.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download