# When should the float and int variables be put in sketch?

I did a little project from a book and in the sketch they put the float and int variables in after the function withing the { } of that function. The sketch did not work properly. So I moved them to the top with all the #define and before the void setup(), then the sketch worked fine.
My question is, is at the top before the set up, functions, and loops the only place they will work and are supposed to go there for the sketch to work properly?

Thanks for the help!

If you need the variable values only inside one function you put the variables inside that function.
If you need the value of that variable (the same value) in more that one function you put the variables after the #define.

That is called a "variable's scope" and you should research that topic to get a good feel for the concept as it's an important feature of most modern programming languages.

Tevor,

The simple answer is when you put variables at the top outside a function they are global through out the sketch. If you put the variables inside a function they are only valid in that function.

That is the simplest way to explain it. What you probably ran into is the variable that was declared in the function was probably trying to get accessed in a different function.

The following declares a b c all globally and usable throughout the whole program.

``````int a = 4;
int b = 2;
int c = 0;

{
c = a + b;
}

void subtraction()
{
c = a - b;
}

void setup()
{

}

void loop()
{
// the variable c would equal 6
subtraction();
// the variable c would equal 2
}
``````

The following would not even compile because variables a, b, c are all declared inside the setup() function and would only be usable inside the setup() function. The functions addition(), subtraction() and even loop() would not know they existed.

``````void addition()
{
c = a + b;
}

void subtraction()
{
c = a - b;
}

void setup()
{
int a = 4;
int b = 2;
int c = 0;
}

void loop()
{
subtraction();
}
``````

Now in the last example even though I used the same names of a and b they are not changed outside the loop function because they were declared in this function. So even though I used the same variables a and b inside the other two addition() and subtraction() functions those variables a and b are local to those functions only. Normally that would be poor programming and make it hard to understand but I used them here just so you could understand what I was trying to get at.

``````int addition(int a, int b)
{
return a + b;
}

int subtraction(int a, int b)
{
return a - b;
}

void setup()
{

}

void loop()
{
int a = 4;
int b = 2;
int c = 0;