0

I have two structs that appears like:

typedef unsigned char byte;

struct my_struct_2 {
int type;
int length; //will be 2 in this case
byte value1; //MSB
byte value2; //LSB
}

struct my_struct_4 {
int type;
int length; //will be 4 in this case
byte value1; //MSB
byte value2;
byte value3;
byte value4; //LSB
}

I want to loop through the "value" members in the struct based on "length" to concatenate the byte values into one number. I am wondering if it is possible to use some sort of stringizing so that I can construct a for loop with a structure similar to this:

int value = 0;
for( int i = 1; i <= length; i++)
{
    value = value << 8;
    value = value & my_struct.value#i#;
}

I want to take advantage of the fact that the structs members are sequentially named.

I know that I can accomplish this task by using a pointer to the first value and incrementing the pointer. I am trying to familiarize myself more with stringizing so please refrain from a pointer like solution. Thanks!

Ryan
  • 33
  • 1
  • 6
  • 1
    Why not an array :`byte value[4];` and `value = value & my_struct.value[i];` – David Ranieri May 23 '16 at 20:18
  • I guess as long as the struct stays this way casting might work as well: `int value = (int)(&my_struct_4_instance.value1);` –  May 23 '16 at 20:27
  • Yes, an array is the right way to do this. – Lee Daniel Crocker May 23 '16 at 20:31
  • The formatting of the structs cannot be modified, as they are from a 3rd party. Is that what you're suggesting? In any case, I could always use a pointer to the first value and address that pointer as an array from then on out. But I really want to know if this can be accomplished using stringizing :) – Ryan May 23 '16 at 20:47
  • "if this can be accomplished using stringizing" No, it can't. – n. m. could be an AI May 23 '16 at 21:54

1 Answers1

0

There is no way to loop through struct fields by constructing names like that. Once a C program has been compiled, any information about names is gone (ignoring information for the debugger); it's all offsets hard-coded into the machine code.

With some C preprocessor abuse you can get something a bit like looping on names, but it's not pretty and definitely not recommended unless you're just doing it for the challenge of doing it.

Chris Emerson
  • 13,041
  • 3
  • 44
  • 66