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

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