Am I missing anything here in my statement about c++?

前端 未结 5 430
慢半拍i
慢半拍i 2021-01-20 12:03

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

5条回答
  •  后悔当初
    2021-01-20 12:54

    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.

提交回复
热议问题