What's the shortest code to write directly to a memory address in C/C++?

orithena picture orithena · Mar 10, 2010 · Viewed 22k times · Source

I'm writing system-level code for an embedded system without memory protection (on an ARM Cortex-M1, compiling with gcc 4.3) and need to read/write directly to a memory-mapped register. So far, my code looks like this:

#define UART0     0x4000C000
#define UART0CTL  (UART0 + 0x30)

volatile unsigned int *p;
p = UART0CTL;
*p &= ~1;

Is there any shorter way (shorter in code, I mean) that does not use a pointer? I looking for a way to write the actual assignment code as short as this (it would be okay if I had to use more #defines):

*(UART0CTL) &= ~1;

Anything I tried so far ended up with gcc complaining that it could not assign something to the lvalue...

Answer

Chris Jester-Young picture Chris Jester-Young · Mar 10, 2010
#define UART0CTL ((volatile unsigned int *) (UART0 + 0x30))

:-P

Edited to add: Oh, in response to all the comments about how the question is tagged C++ as well as C, here's a C++ solution. :-P

inline unsigned volatile& uart0ctl() {
    return *reinterpret_cast<unsigned volatile*>(UART0 + 0x30);
}

This can be stuck straight in a header file, just like the C-style macro, but you have to use function call syntax to invoke it.