简体   繁体   中英

Why block scope at global namespace is not allowed?

I am curious as to why creating a block scope {} outside any function (in global scope) is not permitted.

I am able to do the following:

int main(){

  {
    int i = 4;
  }

    //other stuff

}

but not

{
    int i = 4;
}


int main(){
    //other stuff
}

This issue piqued my interest while implementing a compile time assert, for which I am creating a variable which is to be destroyed immediately after the assert logic is done (to free memory).

I am curious as to why creating a block scope {} outside any function (in global scope) is not permitted.

It would be pointless and misleading. Variables declared outside any function are statically allocated so never go out of scope (except at the end of the program).


Edit: to make a variable exist transiently on program startup, you can do something like:

static auto throwaway_name = [] () { MyClass myVar; return 0; } ();

The only thing this allocates statically is an int (which might get optimised out, I'm not sure).

Why block scope at global namespace is not allowed?

Only declaration statements are allowed in the global namespace by the grammar. No block statements or expression statements.

Let's say that the language was changed to allow block statements in namespace scope. Think about what should the behaviour be. When are those statements executed? In what order?

PS main must return int .

6.3.3 [basic.scope.block]
A name declared in a block (8.3) is local to that block; it has block scope. Its potential scope begins at its point of declaration (6.3.2) and ends at the end of its block. A variable declared at block scope is a local variable

You can't have a nameless block scope in the global namespace scope.

But you can introduce a namespace

namespace N {
  int i = 4;
}

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