Re: [Dev-C++] Static in member function
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-09-20 09:46:31
|
If I do
// Example 1
const char* myfunc(int i) {
static char my_buf[10];
sprintf(my_buf,"%d",i);
return my_buf;
}
the my_buf variable is actually a global variable but without a global
name. It is similar to
// Example 2
static char my_buf[10];
const char* myfunc(int i) {
sprintf(my_buf,"%d",i);
return my_buf;
}
with the exception that in the first case, noone in the same or other
source files may access my_buf, while in the second case everyone in the
same source file may access the my_buf[] variable, but the linker will not
export the variable name so code in other files will not be able to access
it.
If I then finally do:
// Example 3
char my_buf[10];
const char* myfunc(int i) {
sprintf(my_buf,"%d",i);
return my_buf;
}
then I'm all the way to a normal global variable, accessible by anyone.
In C++, there is one more alternative for the static keyword:
// Example 4
class MyClass {
protected:
static char my_buf[10];
public:
const char *myfunc(int i);
};
char MyClass::my_buf[10];
const char* MyClass::myfunc(int i) {
sprintf(my_buf,"%d",i);
return my_buf;
}
where everyone inherriting from MyClass may access MyClass::my_buf[]
since it is in the 'protected' section of the class definition, but where
all objects instanced from MyClass or a descendant of MyClass will share
the same variable. This is because MyClass::my_buf[] is a global variable
with a compile-time access restriction - in this case 'protected'.
In short, whenever the static keyword is used, there will be only one
instance of the variable, but depending on where the static keyword is
used, the access scope of the variable will be either a single file, a
sungle function or a single class.
/Per W
On Sat, 20 Sep 2003, Oladipo Odumosu wrote:
> Per Westmark's right, they would share the same variable, tho i'm not sur=
e why... any answers would be appreciated... thanks
>
> NP
>
>
>
>
> ---------------------------------
> Want to chat instantly with your online friends?=A0Get the FREE Yahoo!Mes=
senger
|