What is a C ++ static keyword with curly 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 static do there? it was also spammed elsewhere ... The code was almost built with static {} everywhere. I lost the source code somewhere, so this is the only thing I have, but it was like this code above: there are no variable declarations, so I don’t understand it.

+4
source share
3 answers

I think this is Java, not C ++, which would mean a static initialization block .

+9
source

I assume this is really java code and a java static block. Basically, a block that runs more or less when a static variable is initialized. (when the class is loaded, but I'm actually not ready to answer questions with java tags).

+6
source

The static keyword documentation in MSDN states can be used in the following situations:

  • When you declare a variable or function in the file area.
  • When you declare a variable in a function ...
  • When you declare a data item in a class declaration
  • When you declare a member function in a class declaration ...

The use of the static to declare a local scope is not specified here, so it is not valid.

If you try to write it in the function body:

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

this will result in the error 'C2143: syntax error: missing'; ' before '{' " because a variable declaration is expected. If you replace static{ with static;{ , the static keyword is ignored, so your code becomes compiled, but the compiler still warns you: "warning C4091: 'static': is ignored to the left of 'int' when the variable is declared .

If you try to write it outside the function body, this will result in the error "C2447: '{': the function header is missing (formal list in the old style?) , Because the function declaration is expected.

+2
source

Source: https://habr.com/ru/post/1398229/


All Articles