Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to declare something "volatile const" in C but only "volatile" in C++?

I was using a header file in my project that had the following define(s):

#ifdef __cplusplus
  extern "C" {
#endif 

#ifdef __cplusplus
  #define   __I     volatile             /*!< Defines 'read only' permissions*/
#else
  #define   __I     volatile const       /*!< Defines 'read only' permissions*/
#endif

The __I is used as follows in another header file:

    typedef struct {   
    // more members before         
      __I  uint32_t  CR;   /*!< GPIO Commit*/
    // more members after

    } GPIOA_Type;

#define GPIOF_BASE                      0x40025000UL
#define GPIOF                           ((GPIOA_Type *) GPIOF_BASE)

My question is why would the __I be made const in C but not in C++? You can still modify the value CR is pointing to since you have the address, but am just curios why the definition of __I is different.

For anybody interested what this is for or from, the __I defines are from IAR Embedded Workbench ARM for Cortex-M4 , and the struct is from Texas Instruments LM4F120H5QR CMSIS files.

like image 412
SoftwareDev Avatar asked Oct 19 '14 21:10

SoftwareDev


People also ask

Can we use const with volatile in C?

Yes a C++ variable be both const and volatile. It is used in situations like a read-only hardware register, or an output of another thread. Volatile means it may be changed by something external to the current thread and Const means that you do not write to it (in that program that is using the const declaration).

Can we declare a variable both as volatile & const in C?

Yes, it is possible. The best example is Status Register in controllers, in the program we should not modify this Status Register so it should be a constant.

Can we use const and volatile together example?

Another use for a combination of const and volatile is where you have two or more processors communicating via a shared memory area and you're coding the side of this communications that will only be reading from a shared memory buffer.

Can we use both volatile and const keyword together?

Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, in the example in FAQ 8, the timer structure was accessed through a volatile const pointer.


1 Answers

In C++, const variables at file scope default to static linkage, which wouldn't be desired for memory-mapped GPIOs. The "right" fix for that is the extern keyword, but that can't be used here, since evidently __I needs to work with class members as well. So eliminating const makes the default linkage extern, as desired.

like image 118
Ben Voigt Avatar answered Sep 28 '22 04:09

Ben Voigt