简体   繁体   中英

What does c++ static keyword do with braces?

I found this code somewhere, perlin noise generator, I think:

static {
    for(int i=0; i<512; i++) perm[i]=p[i & 255];
}

What does the static do there? it was spammed in a lot other places as well... The code was practically built with static{} everywhere. I lost the original code somewhere so thats the only thing I have, but it was like that code above: no variable declarations there, which why I dont get it.

我认为这是Java,而不是C ++,这意味着它是一个静态初始化块

My guess is that it is in fact java code and java static block. Basically, the block that is executed more or less when the static variable would be initialized. (when the class is loaded, but actually I'm not ready to answer questions tagged java).

Documentation of the static keyword at MSDN states it can be used in the following situations:

  1. When you declare a variable or function at file scope..
  2. When you declare a variable in a function...
  3. When you declare a data member in a class declaration
  4. When you declare a member function in a class declaration...

Using static keyword to declare a local scope is not stated here, thus invalid.

If you try to write it in the body of function:

void foo(){
    static{
        int i = 0;
    }
}

it will lead to "error C2143: syntax error : missing ';' before '{'" because variable declaration is expected. If you replace static{ with static;{ , static keyword is ignored so your code becomes compile-able but compiler will still warn you: "warning C4091: 'static ' : ignored on left of 'int' when no variable is declared" .

If you try to write it outside of the body of function, it will lead to "error C2447: '{' : missing function header (old-style formal list?)" because function declaration is expected.

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