0

We have a c program with a lot of files and we are wondering one specific thing.

We are compiling it with C51.

If, lets say in one of the files, I declare a few variables like:

unsigned char xdata a;
unsigned char xdata b;
...
//etc
unsigned char xdata z;

Will their addresses be incrementing and in the same order? as they are declared?

I realize that incrementing addresses can be achieved using arrays or structs or that I can assign fixed addresses of choice but that is not the question.

  • Not cecessarily, the compiler is free to arrange variables in memory in any order. Why do you care? – Jabberwocky Oct 16 '19 at 09:56
  • Which problem do you want to solve with consecutive addresses? – Gerhardh Oct 16 '19 at 09:56
  • Also read [this SO article](https://stackoverflow.com/questions/58405571/how-are-global-variables-stored-in-memory) – Jabberwocky Oct 16 '19 at 09:59
  • You must not assume any special arrangement of variables in memory. Also if they were located at adjacent addresses, you would not gain anything. It is not legal to take address of one variables to access another variable. – Gerhardh Oct 16 '19 at 09:59
  • A compiler might organise variables by type, when translating them from its internal representation to code. It might organise them alphanumerically within that. – Weather Vane Oct 16 '19 at 10:02
  • You should use a memory analyser such as CheatEngine to inspect your compiled program and confirm this yourself, however it may change once you recompile so this should only be used for dirty hacks. – user9385381 Oct 16 '19 at 10:02
  • @user9385381 looking at the generated assembly code is much simpler than using CheatEngine and he is on a microcontroller, so CheatEngine doesn't apply anyway. – Jabberwocky Oct 16 '19 at 10:03
  • @Jabberwocky That is absolutely subjective EDIT: Oh nevermind didn't see the microcontroller thing – user9385381 Oct 16 '19 at 10:04
  • @Jabberwocky and Gerhadh I just happen to run into a very specific situation in which I could have used a pointer to adjust some variables... provided that the addresses were in order. But as it it appears that it would not be wise to assume that that is the case, I simply wrote a couple of lines more to achieve my goal. We are talking about just 8 bytes so it is not a big deal, but still it made us wonder. – bas knippels Oct 16 '19 at 10:37

1 Answers1

1

Will their addresses be incrementing and in the same order? as they are declared?

No, you can't know or assume anything about this. They may be allocated in any order on the stack, or in registers, or not allocated at all. The only time when allocation order is guaranteed is when declaring arrays and structs.

In addition, you can't use pointer arithmetic on anything that's not an array, or you risk running into various subtle undefined behavior bugs.

Lundin
  • 195,001
  • 40
  • 254
  • 396