简体   繁体   中英

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

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 missing? I'm teaching my nephew to program, and he was trying to put a while loop before main. He's pretty young, I want to give him a hard simple rule that he can understand.

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.

  • 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

是的 - 你不能在函数之外粘贴随机可执行代码。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM