Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language : how to interpret this #define?

I've found this snippet on a website :

#define DISPLAY_CR  (*(volatile unsigned int *) 0x4000000) 
DISPLAY_CR = somevalue;

that is supposed to describe DISPLAY_CR as a volatile unsigned int pointer to the adress 0x4000000

What I don't understand is why :

  • the double parenthesis imbrication ?
  • the two stars using (why two stars and not only one ?)
like image 386
loloof64 Avatar asked Jan 18 '26 03:01

loloof64


2 Answers

The extra parentheses are standard practice in macros. Macros are expanded in copy-and-paste fashion, so without the parentheses, the precedence may be altered depending on the context.

Ignoring the extra parentheses, your code expands to:

*(volatile unsigned int *) 0x4000000 = somevalue;

which is equivalent to:

volatile unsigned int *p = 0x4000000; // Treat this as the address of a volatile unsigned int
*p = somevalue; // Write to that address

which hopefully should be clearer.

like image 148
Oliver Charlesworth Avatar answered Jan 19 '26 18:01

Oliver Charlesworth


The extra parenthesis are to stop the macro from being corrupted by surrounding tokens. the 'stars' are use to cast the address to a pointer, then dereference it, to get the value at its address

like image 44
Necrolis Avatar answered Jan 19 '26 17:01

Necrolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!