why the way of using variables affects size of compiled sketch?

Why this code

int i;
void setup() {
  i=5;
}
void loop() {}

takes more (478 bytes) flash than this (466 bytes)

int i;
void setup() {
  int i=5;
}
void loop() {}

What is advantages and disadvantages of both codes?

The second bit of code defines two different variables (both called i) in different scopes. The first bit of code defines only one variable called i in the global scope.

I'd bet the compiler is detecting that nothing is done with the i in the inner scope, so it doesn't bother assigning 5 to it - it just optimizes it out.

In the first case, the global i is equal to 5 after setup runs. In the second case, the global i will probably be 0 (or might just be whatever the last value was in memory there) since you never assign to it.

nppc: Why this code

int i;
void setup() {
  i=5;
}
void loop() {}

takes more (478 bytes) flash than this (466 bytes)

int i;
void setup() {
  int i=5;
}

void loop() {}




What is advantages and disadvantages of both codes?

Well I will leave it to the smarter software gurus to explain the why, but the what is that the first example is using one variable, a global one called i. The second example has two variables defined, a global one called i and a local variable only 'visible' inside the function called setup also called i. So in the second example there are two different variables defined, both called i. There is a difference in the way the variable must be passed to the startup function in the first example compared to how it is a separate locally defined variable in the second example. This concept is called the 'scope' of a specific variable, and is one of the fundamental concepts of a well structured programming language.

Typical guidelines is that variables should be locally defined if they are only used inside a function, however if a variable must be shared between functions then defining it as a global is permitted. Global variables are generally discouraged unless there is an explicit reason to use them, however in small sketches for microcontrollers they tend to be favored by many, me included, as a way to keep all variable definitions and assignments in one place.

At least I think that is how it all works, my words may we wrong, but I do think I understand the concept of scope of a variable.

Lefty