Question:
static and shared variables?
iamxsj
2006-07-10 05:15:50 UTC
if I create a class with static members in it, and then fork it, will the static members shared between the process? ie, if in 1 proc, I increment the variable, and if I retreive in the other, will it reflect the changes? i am thinking no...but what say thou? and y?
Four answers:
Sean I.T ?
2006-07-10 05:21:01 UTC
If you declare a variable to be static in your Class, then the value of it will not change. You are declaring it to have that value so you cannot modify it or change it. If you do change it and increment it in a method in that class, then it will give out an error because you declared it as a static value.



This is for JAVA. I dont know what the rules are for the other languages.



However, you CAN access that variable from a different Class but since its static, you will only receive the value that you set it to. If you want to modify it, I suggest you make it public instead.



Static variables are used because its value will not change. There is no use for you to call it static if you are going to change it. Its just not the way to program. For example, if I have a variable called salesPercent and its a static value of 8.5%, then I would make it a static variable because that value will NEVER change. If you want to change it, then just declare a different variable in your method or procedure.
Vj.
2006-07-10 05:37:07 UTC
In Java the value of static variable is shared across instance of objects of the same class. Also you can access a static variable without creating an instance of the object.



http://www.developer.com/java/other/article.php/1025601

http://mindprod.com/jgloss/static.html
2006-07-10 05:29:34 UTC
Try it and find out! As you don't specify a language it's hard to know for sure - but if you write a short test app you can find out for yourself in minutes!
alakit013
2006-07-10 05:32:03 UTC
#include

#include



/*

Output:

starting: 1

child process: 2

*/

class c1

{

static int i;

public:

static int get( void ) { return ++i; }

};



int c1::i = 0;



int main(void)

{

printf( "starting: %d\n", c1::get());

switch( fork() )

{

case ( pid_t ) (-1):

return 1;

case ( pid_t ) 0:

printf( "child process: %d\n", c1::get());

return 0;

default:

return 0;

}

return 0;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...