Search code examples
cmemorypointersembeddedsdcc

How to better read a value from an address that points to an address


I am wondering if there is a better way to write this:

void readtcp_c(unsigned char c)
{
    volatile char *a;
    volatile int *p;
    volatile int *q;

    a = (char *)APPLE_REG_A;    // a = memory mapped address for REG A
    *a = c + 128;               // store c + 128 in REG A

    p = (int *)APPLE_SUB;       // p = address of 6502 sub
    *p = TCP_WRITE;             // store TCP entry point in address p

    p = (int *)SOFTCARD;        // p = address of softcard address
    q = (int *)*p;              // q = softcard address
    *q = 0;                     // write 0 to softcard address
}

IANS, I have to read/write to specific addresses. 'a' is simply a write to a memory mapped register (6502). The next two lines are similar, except that I am writing the address of a 6502 entry point to be used later. The last 3 lines is where I have to write a 0 to the address stored in SOFTCARD. Writing to this address triggers the call to the aforementioned entry point.

It's the last 3 lines that I think can be shorter. Perhaps not. If the other pairs can be written as a single line that'd be great too. The code works and compiles (sdcc) without error or warning.

Thanks.

Update: I guess I could replace:

    p = (int *)SOFTCARD;            // p = address of softcard address
    q = (int *)*p;                  // q = softcard address
    *q = 0;                         // write 0 to softcard address

with:

    p = (int *)*(int *)SOFTCARD;
    *p = 0;

It compiles without warning and runs. But is it readable? Thanks again.


Solution

  • This should do it. I just replaced the variables by their definition after adding volatile (and also a pair of parenthesis)

    void readtcp_c(unsigned char c)
    {
        *((volatile char *)APPLE_REG_A) = c + 128;
        *((volatile int *)APPLE_SUB) = TCP_WRITE;
        *((volatile int *)*((volatile int *)SOFTCARD)) = 0;
    }
    

    The compiler is perfectly capable of generating good code from your first version though. I like your step-by-step code better.