Read a static variable of a function from inside another function?

 

I want to know if this is possible?


void fun()

{

static int a;


a++;

}


void readOrChange()

{

// read [or change] static int 'a'

// something like:

int b = a.fun();

a.fun() = 3;

}


Thanks for any help!

 
dr34m3r:

I want to know if this is possible?


void fun()

{

static int a;


a++;

}


void readOrChange()

{

// read [or change] static int 'a'

// something like:

int b = a.fun();

a.fun() = 3;

}


Thanks for any help!

 

No, by definition.


The idea of a static variable that is local to a function is to prevent this.


If I were writing in C there are a few workarounds, not sure how many of these will work in mql4.

(probably 1 and 2. ) 3 is intresting though because it highlights the fact that static variables continue to exist

even outside their function calls, unlike "automatic" variables which spring into existence when the function is called.


1) Use a single function to do what you want as follows:


#define XX_START 1

#define XX_STOP 2


// to start

stop_start(XX_START,parameters for starting )

...

// to stop

stop_start (XX_STOP, parameters for stopping)


Your static variable is contained within stop_start so there is no access problem.


2) Use a global static, with a name nobody else is likely to syumble upon.


3) (Almost certainly does not work in mql4 since pointer arithmatic is not allowed)


int *start

{

static int a;

a=1;


return &a;

}


int * stop

{

int *a;


*a=2; // changes or accesses value of a in start.


}

p=start()

p=stop(p)

 

Ok, thank you very much for your reply!

Reason: