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

4

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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