You can\'t have code outside of functions except for declarations, definitions and preprocessor directives.
Is that statement accurate, or is there something I\'m mi
Well, there's namespaces...and the stuff Adam Rosenfield mentioned...and there's also exception try/catch that can be sort of external to functions. Unfortunately, I can't remember the syntax and can't find it with google.
Yes, every kind of statement that does something must reside inside a context that can use it (this doesn't apply to variable initialization).
This because C++ is a structured programming language that encloses its behaviour inside procedures, as opposed to unstructured ones in which you have just one level of code and no scopes.
Yes- you can't stick random executable code outside functions.
Not quite -- you can also put expressions in global variable declarations:
int myGlobalVar = 3 + SomeFunction(4) - anotherGlobalVar;
But you can only put expressions here, which have to evaluate to the value you're initializing the global with. You cannot put full statements (no blocks of code, no if
statements, no loops, etc.). This code will get executed before main()
gets a chance to run, so be careful with what you do here. I'd recommend against calling functions in global initializers unless you can't avoid it.