I am currently reading the PostgreSql code. Here is an excerpt from the buffer manager:
static void WaitIO(volatile BufferDesc *buf);
static bool StartBufferIO(volatile BufferDesc *buf, bool forInput);
static void TerminateBufferIO(volatile BufferDesc *buf, bool clear_dirty,
I know the volatile keyword is usually used for device drivers and in embedded systems. There is an explanation of the keyword.
When the keyword volatile is used in the type definition it is giving an indication to the compiler on how it should handle the variable. Primarily it is telling the compiler that the value of the variable may change at any time as a result of actions external to the program or current line of execution. (Source)
So why are certain function arguments declared as volatile? I don't expect that DMA changes the pointer location. So what happens here?
volatile BufferDesc *buf
means that the data that buf
points to is volatile, not that the pointer contained by buf
is volatile. (That would be BufferDesc * volatile buf
.)
From the page you linked to:
On the other hand, if you have a pointer variable where the address itself was volatile but the memory pointed to was not then we have:
int * volatile x;
Re this part of your question:
So why are certain function arguments declared as volatile?
Presumably because the data it points to can change in a way that the compiler wouldn't necessarily know about. The volatile
keyword is there to prevent the compiler applying optimizations that assume the data doesn't change in ways it doesn't know about.