Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can do this on initialization for a struct Foo:

Foo foo =  {bunch, of, things, initialized};

but, I can't do this:

Foo foo;
foo = {bunch, of, things, initialized};

So, two questions:

  1. Why can't I do the latter, is the former a special constructor for initialization only?
  2. How can I do something similar to the second example, i.e. declare a bunch of variables for a struct in a single line of code after it's already been initialized? I'm trying to avoid having to do this for large structs with many variables:

    Foo foo;
    
    foo.a = 1;
    foo.b = 2;
    foo.c = 3;
    //... ad infinitum
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
457 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this:

Foo foo;
foo = (Foo){bunch, of, things, initialized};

This will work if you have a good compiler (e.g. GCC). You might need to turn on C99 mode with --std=gnu99, I'm not sure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...