Using EEPROM outside a function

Hello, cannot find information so hope you can explain me.
We have to methods of reading from memory EEPROM.read which reads single byte and EEPROM.get which reads the number of bytes equal to the type of variable we are reading to.
If you compile such code:

#include <EEPROM.h>
byte variable1 = EEPROM.read(10);
void setup() {
//any code here
variable1 += 5; //doesn't matter what here is just for the purpose of an example
}
void loop() {
//any code here
}

as you can see I use EEPROM.read outside of any function and compiler considers it to be appropriate. But if I compile such code:

#include <EEPROM.h>
long variable1;
EEPROM.get(20, variable1);
void setup() {
//any code here
variable1 += 5; //doesn't matter what here is just for the purpose of an example
}
void loop() {
//any code here
}

compiler considers it to be error using EEPROM.get outside of a function, so I need

#include <EEPROM.h>
long variable1;
void setup() {
//any code here
EEPROM.get(20, variable1); 
variable1 += 5; //doesn't matter what here is just for the purpose of an example
}
void loop() {
//any code here
}

As for the purpose of the post it is the first thing pure curiosity why this way not other and the second thing wanted to declare global variables in one block and I see I need to do it partially in void setup

None of your code compiles because you have omitted the () for both setup and loop functions.

If you change your 2nd code to the following it compiles...

long variable1 = EEPROM.get(20, variable1);
1 Like

agree, its my typo about ().
is it safe to use EEPROM.get in this way? no pitfalls?

Why do you want to use EEPROM.get() outside of a function ?

Why not declare the global variable as normal then use EEPROM.get() in setup(), loop() or any other function ?

1 Like

Not sure there is any advantage in doing it that way. I prefer to call from within setup... then all initialisation has been completed.

Just for the sake of uniformity, all variables declared and got their values in one place of code but as far as I can see its considered to be not the right way so I do it as you told, use EEPROM.get in the setup
Thank you for answers

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