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

前端 未结 5 431
慢半拍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:31

    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.

    0 讨论(0)
  • 2021-01-20 12:41

    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.

    0 讨论(0)
  • 2021-01-20 12:45

    Yes- you can't stick random executable code outside functions.

    0 讨论(0)
  • 2021-01-20 12:48
    • For your nephew:
      no, you can't do it.
    • For yourself:
      The compiler's input is technically what you get after the preprocessor is run. So, let's leave preprocessor out. After it has worked, you get a C++ program which is a sequence of declarations. Some delcarations may also be definitions, and some definitions (like function definitions) may have statements inside them.
      HTH
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题