Risusdan
Risusdan

Reputation: 91

What's the meaning of this kind of variable declaration?

I saw one way that I can't understand clearly to declare a variable using C (since it's just little part in the whole embedded system program, I've tried to reproduce it simpler below).

#include <stdio.h>

typedef volatile unsigned char XBYTE;
#define var (* (XBYTE * )(0x0100))

int main()
{
    printf("Hello World\n");
    printf("the address of var is %x\n",&var);

    return 0;
}

I'm pretty sure that the fragment is about the "var" which will be allocated at the address 100h, but the question is that I can't tell how it works by pointer.

Besides, is there any potential problem while making a declaration like this?

thanks

Upvotes: 0

Views: 100

Answers (1)

W&#246;r Du Schnaffzig
W&#246;r Du Schnaffzig

Reputation: 1051

Yes, the code can be compiled and is valid.

The volatile keyword means that the variable may change it's value without explicitely writing to it, e.g a timer register. So XBYTE is a type referring to an unsigned char, which is volatile, in addition. However, it's not referring to an actual memory location up to know, it's just the typedef for any such volatile register of type unsigned char. This is where the #definecomes in. If breaked down, it casts the int valued 0x0100 constant into a pointer to XBYTE. Then in a second step it defers that pointer to let one access that memory location. So we end up with a means to access volatile uchar @ 0x100.

As a remark, this is the only way to let C code refer to an explicit constant memory address without runtime overhead.

Upvotes: 2

Related Questions