What is the best practice here?
I have a char array that is [85] that I use to read in from Serial. Should I be passing that into a function like
void getSerial(char* x)
Or should I just use it within the function like any other global variable? The variable is used for many different functions, all involve reading from the serial.
I suspect it will make little difference once the compiler is finished doing its stuff. And using a global variable will probably make the program easier to follow and less error prone.
...R
If the code is usable in multiple locations or is cluttering up another function then for sure use a separate function.
Thanks for the reply.
What about if I had a function where I had say void stuff(String x)? Does that allocate a string dynamically if I'm not passing any user input, just two different strings that I hardcode with F("TEST").
EH
Somewhere I have stuff(F("TEST")) and stuff(F("TEST2")). Is that a potential memory issue?
It will cause dynamic allocations, weather or not that's an issue to you is a different question.
F() uses PSTR, so you can do this instead:
//Inside a function
char *test = PSTR( "TEST" );
char *test2 = PSTR( "TEST2" );
//Or globally
char test[] PROGMEM = "TEST";
char test2[] PROGMEM = "TEST2";
stuff_progmem( char *str ){
//Access str using pgm_read_byte funtions.
}
EDIT: modified the code to show both local and global declarations.
That was very informative, thankyou.
One final question regarding memory...what about if I were using a struct or a JSON like (GitHub - interactive-matter/aJson: aJson is an Arduino library to enable JSON processing with Arduino. It easily enables you to decode, create, manipulate and encode JSON directly from and to data structures.) object? What would be the best practice for that, if I were to be continually writing to the object and sending it somplace else? Would it be wise to delete the object then declare it again or just leave it and rewrite its fields?