Hi
I want to know that what is static block in c or c++ with an example? I know what is static but what is the difference between static and static block?
Hi
I want to know that what is static block in c or c++ with an example? I know what is static but what is the difference between static and static block?
In C++ there is the concept of an anonymous namespace.
foo.cpp:
namespace {
int x;
int y;
}
to get the same effect in C
foo.cpp:
static int x;
static int y;
In simple terms the compiler does not export symbols from translation units when they are either declared static or in an anonymous namespace.
There is no concept with the name "static block" in C/C++. Java has it however, a "static block" is an initializer code block for a class which runs exactly once, before the first instance of a class is created. The basic concept 'stuff that runs exactly once' can simulated in C/C++ with a static variable, for example:
int some_function(int a, int b)
{
static bool once=true;
if (once)
{
// this code path runs only once in the program's lifetime
once=false;
}
...
}
This is not thread-safe however. Getting this working right in the presence of multiple threads can be difficult and tricky sometimes.
Another alternative is that you might be looking for the analogy of a static block in Java. A block of code that is run when the application is loaded. There is no such thing in C++ but it can be faked by using the constructor of a static object.
foo.cpp:
struct StaticBlock {
StaticBlock(){
cout << "hello" << endl;
}
}
static StaticBlock staticBlock;
void main(int, char * args[]){
}
HOWEVER. I've been bitten by this before as it's a subtle edge case of the C++ standard. If the static object is not reachable by any code called by main the constructor of the static object may or may not be called.
I found that with gcc hello will get output and with visual studio it will not.