user56607: if i declare a var in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. here is the code:
#include "Servo.h"

void setup() {
    Servo servo1;
    int x_key = A0;
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

    int x_position = 90;
}

void loop() { 
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}


user2967: Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a { and a }) is only visible inside those braces.
If you want to reference a variable in both setup() and loop(), you have to make it a global variable, defined at the top of your code.
#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here



void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() { 
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}


56607: <p>if i declare a var in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. here is the code:</p>

<pre><code>#include "Servo.h"

void setup() {
    Servo servo1;
    int x_key = A0;
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

    int x_position = 90;
}

void loop() { 
    if (analogRead(A0) &lt; 512) {
        x_position++;
        servo1.write(x_position);
    }
}
</code></pre>
 2967: <p>Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a <code>{</code> and a <code>}</code>) is only visible inside those braces.</p>

<p>If you want to reference a variable in both <code>setup()</code> and <code>loop()</code>, you have to make it a global variable, defined at the top of your code.</p>

<pre><code>#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here



void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() { 
    if (analogRead(A0) &lt; 512) {
        x_position++;
        servo1.write(x_position);
    }
}
</code></pre>
