Declaring variables globally vs in loop()

I saw a simple example sketch that has an input on pin A0 that is saved as int variable. The variable is declared in the loop(): int sensorValue = analogRead(A0);. It would seem to me that it would be better to declare the variable globally before the loop() first and just changed the value each time through the loop(). Which is more efficient?

You cannot declare global variables in loop() or any other function

The scope of a variable declared in a function is limited to that function, so I suspect that the code does not do what you think. Can you post it here ?

It’s not a question of efficiency, it’s a question of limiting scope to the minimum necessary.

If a variable doesn’t need global scope, it shouldn’t have global scope.

There can be tiny efficiencies (and losses) in using global variables...

A global var has its memory and address fixed at build time the references are a constant in your code, local vars are created and disposed of during program execution (by the compiler) as the scope changes.

This can add microseconds to the execution time at specific points in the program.
Not usually a problem, but in time-critical code, those uS may affect your expectations.

As Awol notes, a variable should be limited in scope as much as possible. It’s a software engineering principle, intended to help you avoid shooting yourself in the foot. If you make something global and there’s a bug in your code involving that thing, the problem could be anywhere in your code. If instead, it’s local to a for loop, it’s going to be a lot easier to track down.

Generally, Arduino programs you see here tend to be fairly small, so the risk of using globals is not as severe as in some multi-million line monster running a water treatment plant. Even in little programs though, good basic principles can make your life easier.

Keep in mind, "creating" local variables is not a difficult task for a microprocessor - it only has to add to the stack pointer upon calling, and subtract from it on return. Same overhead for any number of local variables.

As lastchancename said, there are code generation differences when using a variable when it is a global or a local and it can make a difference in code size and execution speed.
This is particularly true on the AVR where there are limited addressing modes.

Look at the assembler code generated for each.
From what I've seen a global will often generate less code to access the contents than a local.
This is particularly true if referencing a structure since the AVR has limited addressing modes.

For many applications it doesn't matter but in some cases it can make all the difference.

--- bill

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.