n00b question

Hi,

I've got a question that Google won't answer and I'd really appreciate some help :) I'll explain with code rather than describing it:

int counter = 0;

void setup(){

Serial.begin(9600);

}

void loop(){

increment(counter); Serial.println(counter); delay(100);

}

void increment(int tempVar){

tempVar++; return;

}

Basically what I'm expecting to see at the terminal is:

1 2 3 4 5 6 ...etc

Instead (which is obvious to you guys that know what's going on) I get:

0 0 0 0 0 0

Now I know that it would work as such:

void loop... counter = increment(counter); ...

int increment(int tempVar){ tempVar++; return tempVar; }

...but basically, I want to know if it's possible to pass a global variable as an argument to a function and have that function manipulate it internally with a local variable and store the result of the manipulated internal variable into the global variable without referring to the global variable directly in said function. My programming experience is limited to bits and pieces of various languages, but I'm pretty sure I've done this before in another language. Or am I being daft? :)

This is driving me mad, I appreciate any input!

There's no need to pass a global to a function. If you want to manipulate any variable, you might want to look at references. http://arduino.cc/en/Reference/Pointer

I want to know if it's possible to pass a global variable as an argument to a function and have that function manipulate it internally with a local variable and store the result of the manipulated internal variable into the global variable without referring to the global variable directly in said function.

Yes, it is possible. The global variable needs to be passed by reference:

void increment(int [glow]&[/glow]tempVar)

You may need to add the function prototype. The IDE has problems with functions with reference arguments. Add this before setup().

void increment(int [glow]&[/glow]tempVar);

or the original C way

int counter = 0;

void setup(){
 Serial.begin(9600);
}

void loop(){
 increment(&counter); //pass a pointer to counter as the actual parameter
 Serial.println(counter);
 delay(100);
}

void increment(int *tempVar){ //formal parameter is a pointer to an int
  (*tempVar)++; // increment the contents of the pointer i.e. counter
}

Wow that was quick :o

Thanks guys!

I figured it might be something with pointers (a topic I avoided in my intro to C course at varsity... ignorance is bliss lol). I understand the concept, just never used them. Guess it's time to learn :)

Thanks again!