variable ram use if declared in loop

In this code should there be a difference in ram used during execution of function(x) depending on if x is declared before void loop() compared to declared within it?

int x = 20;
void loop()
{
int x = 20;

function(x);
}

In this code should there be a difference in ram used during execution of function(x) depending on if x is declared before void loop() compared to declared within it?

No. An int uses 2 bytes of memory, whether it is global or local.

The compiler might decide, though, that the variable is useless, and optimize it away.

Local variables are on the stack - they only get created if the function is called, and reclaimed as it
returns.

Global variables take up RAM for the duration.

A variable should be local or static-local if its only used in one function.

When a function is recursive you have to worry about how much the stack can grow.

Sorry I made a mistake,

int x = 20;
int y;
void loop()
{
  int x = 20;
  y = 40;
  ...

  function(y);
}

Would the compiler know that x is not used in function(y) so that more ram is available when executing function(y) - depending on where x is declared?

perigalacticon:
Would the compiler know that x is not used in function(y) so that more ram is available when executing function(y) - depending on where x is declared?

Turn up the warning level in Preferences.

BareMinimum.ino: In function 'void loop()':
BareMinimum.ino:9:7: warning: unused variable 'x' [-Wunused-variable]
   int x = 20;
       ^

Since the compiler knows that the local 'x' is not used anywhere it might not allocate space for it.
There is no warning for the global 'x' so it probably takes up space. If you declare it as 'static int x' the compiler knows that it can't be used by something like an external library so it warns that the value is not used:

BareMinimum.ino: At top level:
BareMinimum.ino:5:12: warning: 'x' defined but not used [-Wunused-variable]
 static int x = 20;
            ^

Ok what if x *= x; is added to the loop so it's used in loop but not in the function. Now is x de-allocated when function is called depending where it is defined? I would like to maximize ram available to function().

perigalacticon:
Ok what if x *= x; is added to the loop so it's used in loop but not in the function. Now is x de-allocated when function is called depending where it is defined? I would like to maximize ram available to function().

Because you use the local 'x' it will take up space on the stack until loop() exits.

Moreover, since local ‘x’ is in-scope for all of function ‘loop()’, the storage space for it can’t be given up when ‘function(y)’ is called from ‘loop()’. Local ‘x’s value must be remembered so it can be used after ‘function(y)’ returns.

Thanks I understand I have to study this.