Pages: [1]   Go Down
Author Topic: refferencing vars in functions  (Read 400 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 25
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

London
Offline Offline
Faraday Member
**
Karma: 8
Posts: 6240
Have fun!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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.
« Last Edit: December 14, 2008, 09:21:15 am by mem » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 25
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Pages: [1]   Go Up
Jump to: