yildizabdullah
yildizabdullah

Reputation: 1971

#define REG(x) (*((volatile unsigned int *)(x)))

What is the meaning of the following macro definition?

#define REG(x) (*((volatile unsigned int *)(x)))

Upvotes: 1

Views: 4021

Answers (2)

The volatile keyword grossly means that the compiler should really access and write the qualified data at each occurrence.

As a stupid example, consider the loop

#define REG(x) (*((volatile unsigned int *)(x)))
for (REG(0x1234)=0; REG(0x1234)<10; REG(0x1234)++)
   dosomethingwith(REG(0x1234)*2);

If you did not put the volatile keyword, an optimizing compiler could (assuming dosomethingwith is inlined) load in a register the content of memory at 0x1234 once (before the loop) and perheps update it only after the loop, and increment and test only the content of the register (without caring to access location 0x1234 in the loop).

With the volatile keyword, the compiled binary code is required to access the 0x1234 location (which probably would be a hardware port or device) at every loop.

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409432

It casts x as a volatile unsigned int pointer, and then dereferences that pointer to get the value of what x "points" to.

Note that x doesn't actually need to be declared as a pointer, it could as well be a literal integer that is then treated as an address to somewhere in memory. Useful on embedded systems or in kernel boot-up code where there are things at fixed addresses.

Upvotes: 4

Related Questions