what is that static used for.. and when is a good time to use it?
Printable View
what is that static used for.. and when is a good time to use it?
If you're talking about static member functions of classes, they are functions that do not require an object to be instantiated from the class before being used.
The static keyword can be used to limit the scope of a function or object -- to a file or a function, for example.
It may also be used to make a block-scope object's lifetime to be the entire execution of the program -- a variable with function scope that retains its value between function calls, for example.
i didnt understand not a word you just said hehe
anyways.. take this for example
its a friends code.. im just tring to understand itCode:
static char textBuffer[1024];
va_list args;
va_start(args, words);
vsprintf(textBuffer, words, args);
va_end(args);
return write(soc,textBuffer,strlen(textBuffer));
The function is declared as static, meaning its scope is limited to the file it is in. You cannot use this function outside of the file it is defined in, because it is static.
If you had a variable inside a function as static, instead of, or possibly along with, the function itself, then that variable would retain whatever value it had the last time the function was called.
Example:
Every time you call this function, the value of x is printed, and then it is incremented. If the variable were not static, two things would happen:Code:void fun( void )
{
static int x;
printf("x is %d\n", x );
x++;
}
1) The value isn't ever initialized, so it would have some random value.
2) The value would not remain retain its information for the next time the function was called.
Static variables are automaticly initialized to zero when created, this is why we can get away without initializing it.
Also, since it is static, it will simply increment as we indended. Meaning: The first time, it will print zero, the second time it will print one, and so on.
Quzah.
thank you.. i get it now =) ( well better then before )
>You cannot use this function outside of the file it is defined in, >because it is static.
You can't use it by name. It can still be called via a function pointer.