0

I'm trying to declare a static C struct. The declaration of the struct is as follows:

typedef struct { int a; int b; int c }dummy_struct; 

However when making the definition of the struct, I want to store a value in c that is calculated using the values in a and b and another constant value.

My initial idea was to store it this way:

static dummy_struct dummy = { .a = 5, .b = 10, .c = CALC_VALUE(0.5, a, b) } 

And then I would define CALC_VALUE as a preprocessor so that I could run some calulations on a, b and the constant value like so:

#define CALC_VALUE(constant, a, b) (constant * (a/2) * (b*3)) 

But my compiler complains every time I do this so I'm resorting to the following method for the declaration:

static dummy_struct dummy = { .a = 5, .b = 10, .c = CALC_VALUE(0.5, 5, 10) } 

Is there a cleaner way to do this without using #defines for 'a' and 'b'

5
  • Why not just store 0.5 in the struct, and then do the calculation where you need the value? Commented Oct 13, 2020 at 18:44
  • Structure members are not variables, they can't be accessed without referring to the variable containing the struct. Commented Oct 13, 2020 at 18:47
  • And you can only use literals and constant expressions when initializing a static variable. Commented Oct 13, 2020 at 18:48
  • @JosephSible-ReinstateMonica The problem is not storing 0.5, it is about being able to access the value in a and b from within the struct declaration. I don't mind using a #define for 0.5, but I want to be able to access a and b as they are both already defined for the struct member. So I was wondering if there is a way to access the value stored in the local member. If you look at my second code snippet, I want to be able to do something like that. Commented Oct 13, 2020 at 18:48
  • @Barmar Ok got it. That is the limitation I'm trying to get past I guess. Commented Oct 13, 2020 at 18:49

1 Answer 1

1

Use a macro to generate the entire initial value of the struct.

#define CALC_VALUE(constant, a_val, b_val) { \ .a = (a_val), \ .b = (b_val), \ .c = ((constant) * ((a_val)/2) * ((b_val)*3)) \ } 

Then you can do:

static dummy_struct dummy = CALC_VALUE(0.5, 5, 10); 
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.