Sharing my experience and thoughts:
I had this code in my project:
void loop() {
static EthernetClient client = server.available();
I have just added this "static" there, based on these thoughts:
"my stack is pretty small! I do not know how much memory client would need from stack. And not doing all the time this function call could speed up the code (reuse when it is already set, not like a temporary, auto variable which has to be initialized on every iteration in this loop())".
But nothing on my HTTP server (EthernetClient) was working anymore: no compile error, not a crash, just client was always zero and never acting on WebBrowser connected to it.
Obvious!
"static" can have two flavors:
-
You define a variable as static and you assign a value to it:
This is OK. Behind the scene the value for this static variable has a copy in ROM (Flash) and will be initialized during startup code executed. The .bss section (see linker script) has all the values to write to static variables before it jumps to main(). So, the variable is initialized, way before you would execute the function, here loop(). -
But when you assign a value to a static variable with the result of the function call - the question is: "when is this function executed?" (and return value assigned)
So, the difference is: to assign the return value of a function call to a static variable needs the execution of this function. "But when will it be executed?"
Potentially, also during the startup code: way before the main(), well before the loop() is called. The function is called "so early" that the function call itself is "too early".
Potentially, this function needs to have the ETH device configured, the network is up and running. But all this is done inside my main(), or the setup() function.
The compiler plus linker plus startup code organizes the code in a way that it will call this function to assign the result to static "soo early" that nothing is ready: the ETH and network is not up and running yet.
So, it has to fail.
So, the definition of a static variable with an assignment of a function call result - is "unpredictable"! Even no compile error, potentially no crash - the call of this function is potentially "too early" (system is not yet ready, not all initialized yet ... and nothing to do to tell compiler "just do it after I did this").
For me: I try to avoid to assign the result of a function call to static variables. I do not want to have code execution during startup, before my main() and setup() was really done.