'volatile' keyword deprecated under some circumstances (C++20)

Here is a simple example sketch compiled under C++20 for an ESP32_C3 (using Arduino IDE 2.3.3). It yields a message that this use of 'volatile' is deprecated.
This design pattern is quite commonly used in Arduino sketches. What is the simplest recommended way of structuring this to avoid such messages?

    volatile uint32_t pulses = 0;

    void setup() {
      Serial.begin(115200) ;
      attachInterrupt(digitalPinToInterrupt(2), toggle, FALLING );
    }

    void loop() {
      noInterrupts() ;
      uint32_t pulses_copy = pulses ;
      Serial.println( pulses_copy ) ;
      interrupts() ;
      delay(1000) ;
    }

    void toggle() {
      pulses += 1;
    }

The warning is here:

C:\Users\6v6gt\AppData\Local\Temp\.arduinoIDE-unsaved2025019-12368-1726qco.z5dh\sketch_jan19b\sketch_jan19b.ino: In function 'void toggle()':
C:\Users\6v6gt\AppData\Local\Temp\.arduinoIDE-unsaved2025019-12368-1726qco.z5dh\sketch_jan19b\sketch_jan19b.ino:14:14: warning: compound assignment with 'volatile'-qualified left operand is deprecated [-Wvolatile]
   14 |       pulses += 1;
      |       ~~~~~~~^~~~

using pulses++; gives a similar warning.

1 Like

Try pulses++; ?

Using

   pulses = pulses + 1;

compiles cleanly.

It appears that "++" and "+=" are deprecated uses, possibly to remind the programmer not to expect atomic operations.

However, a RMW using regular operands is not deprecated, even though that is not necessarily atomic either?

Relevant article: Modern Embedded C++ - Deprecation of volatile - Sticky Bits - Powered by FeabhasSticky Bits – Powered by Feabhas

Appears "register" is changing too.

2 Likes

pulses = pulses + 1 ; // does indeed work
pulses++ ; // does not and gives the following message: . . .

C:\Users\6v6gt\AppData\Local\Temp\.arduinoIDE-unsaved2025019-12368-1726qco.z5dh\sketch_jan19b\sketch_jan19b.ino: In function 'void toggle()':
C:\Users\6v6gt\AppData\Local\Temp\.arduinoIDE-unsaved2025019-12368-1726qco.z5dh\sketch_jan19b\sketch_jan19b.ino:18:3: warning: '++' expression of 'volatile'-qualified type is deprecated [-Wvolatile]
   18 |   pulses++;
      |   ^~~~~~
1 Like

That is an interesting article.
So it looks like the suggestion solution is this:

I guess the "pulses = pulses + 1" variant is OK because the user is considered less likely to believe that it is an atomic operation because one operand appears twice.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.