Static Datatype  
Author Message
Revant





PostPosted: Visual C++ Language, Static Datatype Top

Hello

I am not sure when to use a static data type when coding a win32 program. Can someone pls explain that concept.

Thanks


Visual C++10  
 
 
Simple Samples





PostPosted: Visual C++ Language, Static Datatype Top

Topics such as that are covered very well in many books and tutorials. You can get more complete answers using those.

If you don't know what use a static type is, then you probably don't need it. It would be better if you were to have a specific requirement and then ask what the solution is.

A static type could be used for a variable that is local to a function but is not initialized each time the function is called. A non-static type does not retain a previous value from the previous execution of the function whereas a static type changes only when you change it explicitly in code. A static type could be used in places that a global might be used.

Of course, genral questions such as yours are often asked as homework, in which case it would be better to not answer it for you. It would be more educational for you, even if this is not a question to be turned in for a grade, if you were to read the documentation and then ask specific questions based on what you read.



 
 
einaros





PostPosted: Visual C++ Language, Static Datatype Top


Can someone pls explain that concept.

Static has different meaning, depending on the context.

  • If used in a function, the variable will retain its value for all executions of that function. It will be initialized only once.

void foo()
{
static int myVar = 0;
myVar++; // myVar will be incremented by one, for each execution of foo()
}

  • A class function marked static will be callable without an instance of the class

class Foo
{
public:
static void myFunction()
{
// myFunction can not access non-static members of Foo!
}
};

int main()
{
Foo::myFunction(); // We don't need an instance of the class
}

  • A static data member variable will be usable without an instance of the class, and remain allocated / initialized for the remainder of the application execution

class Foo
{
public:
static int myVar1;
int myVar2;

static void myFunction()
{
myVar1 = 100; // myFunction can access myVar1
// but not myVar2!
}
};

int Foo::myVar1 = 0; // static data members must be initialized

  • A function or variable marked static at namespace or global scope will be local to a translation unit

=== 1.cpp ===

extern int foo;
extern int bar;

int main()
{
foo = 100; // Ok! foo is available from 2.cpp
bar = 200; // error: bar is local to 2.cpp
}

=== 2.cpp ===

int foo;
static int bar;