On Aug 22, 1:34*pm, s0s...@gmail.com wrote:
> On Aug 22, 1:44 pm, ssylee <staniga...@gmail.com> wrote:
>
>
>
> > I'm not sure if I can initialize members of a struct the lazy way. For
> > example, let's say I have a struct defined as below:
>
> > typedef struct _ABC
> > {
> > * * * *BOOL *A;
> > * * * *BOOL *B;
> > * * * *BOOL *C;
>
> > } ABC;
>
> > If I want to initialize all members of the struct as false, is there a
> > way of changing the state of the members all at once like what I have
> > attempted below:
>
> > ABC hi = FALSE; // or something along similar lines as this as this is
> > invalid
>
> The initializer for a structure is usually a brace-enclosed set of
> values:
>
> ABC hi = {FALSE, FALSE, FALSE};
>
> The "lazy" way would be to provide the value of only one member:
>
> ABC hi = {FALSE};
>
> In this case, the rest of the members are automatically initialized to
> zero. Note that this will only work if your 'FALSE' identifier has the
> value 0. I'd recommend you to use the 'bool' type defined in
> <stdbool.h>, along with the macros 'true' and 'false', instead of
> defining your own. Using those macros this technique would work.
>
> In case you want to initialize some of the members to TRUE and the
> rest to FALSE, you can do something like this:
>
> ABC hi = {.A = TRUE, .C = TRUE};
>
> > or would the only way of modifying the members be modifying each
> > member's state individually?
>
> If it's at initialization, you can use the techniques described above.
> Otherwise, if you already have the structure and want to change its
> state, the rules are a bit different. One way that would be similar to
> initialization would be to use a compound literal:
>
> ABC hi;
> ...
> hi = (struct ABC) {FALSE}; // this is assignment, not initialization
>
> In this case, we didn't specify a value for all the members in the
> compound literal, so the rest of them are initialized to zero. Another
> way to do it would be to use memset():
>
> ABC hi;
> ...
> memset(hi, (int) FALSE, sizeof hi);
>
> But this technique is rather cryptic. (Note that I casted 'FALSE' to
> int to emphasize that the second argument to memset() is an int, which
> means that your 'FALSE' identifier should be able to be converted to
> int.)
>
> Sebastian
Thank you for all your suggestions. I guess I was looking for ABC hi =
{FALSE}; but couldn't seem to recall at the moment I was asking the
question.
|