3

I've defined a macro to set my values(C code), for example:

.h file

typedef struct {
    uint8_t details;
    uint8_t info[20];
} values_struct;

#define INIT_VALUES_STRUCT(X) values_struct X = {.details = 0x00, .info = { 0x01 } }

.c file

INIT_VALUES_STRUCT(pro_struct);

but I need to set a "struct array" like:

values_struct pro_struct[10];

and to set default values with a macro, it's possible and how I can do that?

2 Answers 2

4

Redefine that macro as

#define INIT_VALUES_STRUCT {.details = 0x00, .info = { 0x01 } }

And then you can have

struct values_struct pro_struct = INIT_VALUES_STRUCT;
struct values_struct pro_struct_arr[] = { INIT_VALUES_STRUCT,
                                          INIT_VALUES_STRUCT,
                                          INIT_VALUES_STRUCT };
Sign up to request clarification or add additional context in comments.

Comments

1

Why make it complicated with macros when the following works:

#include <stdio.h>
#include <stdint.h>
struct x {
    uint8_t details;
    uint8_t info[2];
};
int main(void) {
   struct x arr[2] = {
       { 1, {5, 6}},
       { 3, {4, 7}}

    };
    // your code goes here
    return 0;
}

9 Comments

Because macros are a good way telling your c code you have these const variables, global variables, global functions, etc.. you share and use in your entire program.It's much more cleaner to use #define VAL 1 in you foo.h file rather than const int value = 1 or use global function/constructors etc.
IMHO const int value = 1 is better than a macro as the compiler knows its type along with its value. Perhaps writing const int VALUE = 1 is slightly better
In the end you know that the preprocessor will replace the value/code you define in the places you used your macro.It's almost the same semantic but the code will be more unclean in my perspective and i'm sure i'm not the only c programmer who thinks this. It's just a convention.. you are free to use what ever you want.
In the case of a structure, a macro-ed initializer is far more readable then the hard-coded one. Not to mention that using a macro means you aren't obligated to change numerous object initializations if you happen to change the structure definition.
Btw For the actual compiled code, with any modern compiler, there should be zero performance difference between the two.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.