Go Down

Topic: refferencing vars in functions (Read 511 times) previous topic - next topic

dbunting

i dont know if this is the proper term but id like to reference a var inside a function

what id like to do is create a function called change_state that takes one argument.  The argument it takes is the name of a var (a boolean)

id like it to wrok something like the following

void change_state (char var) {
 if (var == false) {
   var = true;
 }
 else {
   var = false;
 }
}

boolean open = false;
change_state("open");
//and now open = true
change_state("open");
//and now open = false again


is there a way to do that?

mem

#1
Dec 14, 2008, 03:19 pm Last Edit: Dec 14, 2008, 03:21 pm by mem Reason: 1
In C you need to pass a reference to the variable if you want to change an argument to a function. This is done by passing a pointer to the variable you want to change. In the function you use the C syntax for getting the value that a pointer points to.

Here is your code by way of example.
Code: [Select]

void change_state (boolean *var) {

if (*var == false) {
  *var = true;
}
else {
  *var = false;
}
}

void change_state2 (boolean *var) {
*var = !(*var);
}

void loop(){
boolean open = false;
change_state(&open); // pass a pointer to the open variable
//and now open = true
change_state(&open);
//and now open = false again
}


There are two version of the change_state function, the second one uses the C boolean 'not' syntax to invert the value.

dbunting

brilliant

thank you for answering my question so clearly.

Its been so long since i worked in C and of the 28 pages of the forum that i looked through in SOFTWARE i didnt find an answer to my question that was this clear.

again thank you

Go Up