0

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

3

1 Answer 1

5

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.

6
  • 1
    as a C noob, i only see volatile used in interrupt routines.
    – dandavis
    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
    Sep 15, 2017 at 21:10
  • 1
    @zeta-band: makes sense, thanks for the insight.
    – dandavis
    Sep 16, 2017 at 20:34
  • 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? 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. Nov 20, 2018 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.