Search code examples
cembeddedpowerpc

Tricky Macro in C


I've got such a statement for a PowerPC and don't know how it works

#define XOR(A,D) (*(volatile unsigned int*)(volatile void*)((unsigned char*)0UL + (A)) ^= (D))

which is called(for example)

unsigned int a = 3;
unsigned int b = 50;
XOR((unsigned int)&a,b);

With a gcc for standard PC it does not compile, in my environment it did, so I ask myself: wtf...


Solution

  • It seems to be an unnecessarily convoluted macro for toggling bits at hard-coded addresses. These addresses are probably memory-mapped register addresses. The A and D are clues here: A = address, D = data. So typically if you have a register at address 0x100 and you want to toggle its least significant bit, you might write something like:

    XOR(0x100, 0x01);
    

    A much simpler version would just be:

    #define XOR(A, D) ((*(volatile int *)(A)) ^= (D))
    

    It's not clear why the original author used multiple casts and added the hard-coded address to a NULL pointer. At a guess, the former may be there to get rid of a compiler warning, the latter may have been to allow for a different register base address at some point.