Why in the piece of code below we use "static volatile bool"?
static volatile bool wifi_connected = false;
taken from here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino
-
You could easily answer this question yourself with a little research. Maybe a good book, to start: The Definitive C Book Guide and List001– 0012017年09月15日 14:15:39 +00:00Commented Sep 15, 2017 at 14:15
-
The use of "static" confused me because I thought that static is a variable that remains in memory while the program is running. Thank you for the list of books!plsp– plsp2017年09月15日 14:35:55 +00:00Commented Sep 15, 2017 at 14:35
-
There is a lot about C that is confusing, which is why I recommend a good book or article. A quick search found these examples: Static_(keyword) or C Static Variables and Static Functions Explained with Examples001– 0012017年09月15日 14:52:47 +00:00Commented Sep 15, 2017 at 14:52
1 Answer 1
static
means that the global will only be accessible inside the current translation unit.
volatile
means that while(!wifi_connected){/*...*/}
cannot be optimized to if(!wifi_connected)while(true){/*...*/}
These things are orthogonal. So you would use static volatile when you need both properties.
-
1as a C noob, i only see
volatile
used in interrupt routines.dandavis– dandavis2017年09月15日 19:16:55 +00:00Commented Sep 15, 2017 at 19:16 -
@dandavis volatile is a hint to the compiler that the variable may be changed in another thread or an interrupt routine. This is to tell the optimizer not to get rid of loading the variable from memory each time we check the status.zeta-band– zeta-band2017年09月15日 21:10:43 +00:00Commented Sep 15, 2017 at 21:10
-
In your volatile case - would the compiler also include a jump out of the loop if
wifi_connected
were changed? If not - how would it handle exiting the loop in the (eventual) case that the variable changes?Brydon Gibson– Brydon Gibson2018年11月20日 18:02:52 +00:00Commented Nov 20, 2018 at 18:02 -
@BrydonGibson variables are only checked when you tell them to be checked so the compiler will not introduce a break into the middle of the while body that you didn't put there. The while acts just like a normal while.ratchet freak– ratchet freak2018年11月20日 22:07:05 +00:00Commented Nov 20, 2018 at 22:07
-
I understand. In the given example however, the while loop will run forever even if wifi_connected is changed inside. I guess the compiler wouldn't make that optimization in that scenarioBrydon Gibson– Brydon Gibson2018年11月20日 22:08:23 +00:00Commented Nov 20, 2018 at 22:08