For example, for the dummy function write(int length, const char* text){...}, is there any difference in terms of memory between these two approaches?
write(18,"The cake is a lie.");
or
int len = 18;
char txt[19] = "The cake is a lie.";
write(len,txt)
Bonus: what if there's some repetition? i.e. A loop calls the function repeatedly using an array whose elements are the intended arguments.
I'm asking this question, especially the bonus, in hopes of better understanding how each consumes memory to optimize my efficiency when writing on memory-sensitive platforms like Arduino. That said, if you know of an even more efficient way, please share! Thanks!
It depends on whether
char txt[19]is declared in scope of a function or at a global (or namespace) scope.If in scope of a function, then
txtwill be allocated on the stack and initialized at run time from a copy of the string literal residing in a (read-only) data segment.If at global scope, then it will be allocated at build time in the data segment.
Bonus: if it's allocated in some sub-scope, like a loop body, then you should assume it will be initialized during every loop iteration (the optimizer might do some tricks but don't count on it).
Example 1:
Here
len(anint) andtxt(19 bytes + alignment padding) will be allocated in the program's data segment at build time.Example 2:
Here the string literal
"The cake is a lie."will be allocated in the program's data segment at build time. In addition,lenandtxt(19 bytes + padding) may be allocated on the stack at run time. The optimizer may omit thelenallocation and maybe eventxt, but don't count on it, as it's going to depend on many factors, like whetherwritebody is available, what it does exactly, the quality of the optimizer, etc. When in doubt, look at the generated code (godbolt now supports AVR targets).Example 3:
Here the string literal
"The cake is a lie."will be allocated in the program's data segment at build time. The18will be embedded in the program code.Since you're developing on AVR, there are some additional specifics worth mentioning, namely the application's executable is initially stored in the Flash, and once you "run" it, it is copied to the RAM. It is possible to avoid copying to RAM and keep the data in the Flash using the
PROGMEMkeyword (though to do anything meaningful with the data you will need to copy it to RAM).