sorry this is a very naive question but it keeps bothering me:
When a variable is declared inside the loop() procedure, this variable is actually declared again and again every time the procedure is run, right ? Is looks like a waste of time and ressource... Yet I rarely see variables declared as global variables (i.e. outside any procedure) in the code I have seen so far on the forum.
Is it just bad coding practice or is there another reason ?
I rarely see variables declared as global variables (i.e. outside any procedure) in the code I have seen so far on the forum.
That surprises me as many programs posted use mainly global variables.
It is actually good practice to declare variables in the scope that they will be used, usually in a function. The fact that they are declared over and again in loop() is not a problem unless you want a variable to retain its value between calls to the function, in which case they should be declared as static.
On some processors, local variables are less efficient than globals, because globals are often at a fixed address, whereas locals are addressed relative to a pointer, usually the stack pointer.
Conversely, on other processors, local variables are more efficient, for precisely the same reason.
However, as has already been pointed out, variables should always be defined with the minimum possible scope, for the simple reason of good programming practise.