简体   繁体   中英

c programming default parameters: const struct vs init function

Suppose I have something like:

typedef struct
{
    int parameter1;
    int parameter2;
    void (fp*)(void);
} STATE_T;

and I have various sets of default parameters to start the program(or this segment of the program) in different states.

STATE_T State;

void InitState1()
{
    State.parameter1 = 123;
    State.parameter2 = 321;
    State.fp = Function1;
}
void InitState2()
{
    State.parameter1 = 0;
    State.parameter2 = 1;
    State.fp = Function2;
}

or would it better to use const structs

const STATE_T STATE1 =
{
    123,
    321,
    Function1
}

const STATE_T STATE2 =
{
    0,
    1,
    Function2
}

I suppose in the 2nd case either a pointer can be used or a function to copy a selection of settings:

STATE_T * StatePtr;
StatePtr = &STATE1;

or

void InitState(STATE_T s)
{
    State.parameter1 = s.parameter1;
    State.parameter2 = s.parameter2;
    State.fp = s.fp;
}

After typing out all the examples, it seems like, in the case I want to change all parameters at the same time, using a pointer to const structs would be more efficient, while an init functions would be better for only updating selected parameters that would be relevant. Are there any other advantages or differences to be aware of?

I typically declares some static versions statically ie

static State State1 = {
  .paramater1 = 123,
  .parameter2 = 321,
  .fp   = NULL,
};

static State State2 = {
  .paramater1 = 999,
  .parameter2 = 111,
  .fp   = NULL,
};

Then in an init function assign the statics to get the defaults...

static State * newState(int state) {
  State *foo = calloc(1, sizeof(State));
  assert(foo != NULL);
  if(state == 1) {
    *foo = State1;
    foo->fp = function_fp1;
  }
  else {
    *foo = State2;
    foo->fp = function_fp2;
  }
  return foo;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM