There is an SRC variable of 16 bits, how to create two 8-bit variables, so that one is addressed to the upper part and the second to the lower part of the SRC variable? type construction
uint16_t src; uint8_t b1 = * ((uint8_t *) & src); uint8_t b2 = * (((uint8_t *) & src) +1);
should work but at compilation produces:
MAIN.c (16): error: # 28: expression must have a constant value uint8_t b1 = * ((uint8_t *) & src); MAIN.c (17): error: # 28: expression must have a constant value uint8_t b2 = * (((uint8_t *) & src) +1); MAIN.c: 0 warnings, 2 erros
How to correctly address the variables B1 and B2 that, when changing these variables, the corresponding value in the SRC variable and vice versa change. Sorry for my english :)
C and C++ have different rules
uint16_t src; uint8_t b1 = * ((uint8_t *) & src); // not legal in C (not const), yes in C++ uint8_t b2 = * (((uint8_t *) & src) +1); // not legal in C (not const), yes in C++ #define LOWBYTE(a) * ((uint8_t *) &a) // Assumes Little Endian #define HIGHBYTE(a) * (((uint8_t *) &a) +1) // Assumes Little Endian void main() { uint8_t b1 = * ((uint8_t *) & src); // legal in C and C++ uint8_t b2 = * (((uint8_t *) & src) +1); // legal in C and C++ b1 = LOWBYTE(src); // legal in both b2 = HIGHBYTE(src); // legal in both }
Thanks for the answers :) there are several BUT. The command "b1 = LOWBYTE (src); // legal in both" takes 4 cycles of the processor and that loss in the sum of 8 bars at the same time it's not exactly what you wanted. I want to declare SRC variable 16bit and two variables on 8bit LOWBYTE and HIGHBYTE but so that the change of one caused the change of the other and vice versa. In general, a single address space for these variables. In the bascomAVR it is implemented like this:
Dim Data_wr As Word Dim X_low As Byte At Data_wr Overlay 'LOWBYTE ... Dim X_high As Byte At Data_wr + 1 Overlay 'HIGHBYTE | SRC | adress|0 7|8 15| |HIGHBYTE| LOWBYTE |
You are describing exactly what a union in C would do.