0

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

8
  • 3
    How is xdata defined? Looks like the typeded is incorrect. Commented Feb 9, 2021 at 8:54
  • 1
    #define var (* (XBYTE *)(0x0100)) contents of (virtual) storage location 0x0100. Commented Feb 9, 2021 at 8:58
  • Your var is not a variable, but some l-value Commented Feb 9, 2021 at 8:58
  • 1
    Is this compiling at all? Commented Feb 9, 2021 at 8:59
  • 1
    Please show a minimal reproducible example of this being used in a way which can be compiled and run. Commented Feb 9, 2021 at 9:09

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.