C-Programming Structures

Hi Guys,

here is a question for you:

It is possible to define a structure like

1
2
3
4
struct test {
   int a;
   int b;
};


and create an instance of it:

1
2
3
struct test mytest;
mytest.a = 1;
mytest.b = 22;


Or, create an instance and initialize it at the same time:

 
struct test mytest = { 1, 22 };


Now, is it possible to use Method B, initializing just a bunch of members in a random sequence (example given doesn't work - just for illustration what I mean...)???

1
2
struct test mytest = { b = 22 }; //which fails since b is not defined here...
struct test mytest2 = { b = 22, a = 1 };


Thanks for your advice!

Best,

Axel
Last edited on
You can, in C (C99). And it would look very similar to your code:

struct test mytest = { .b = 22, .a = 1 };

Edit: while C++ does not "officially" support designated initializers, certain C++ compilers may let you do this, I'm thinking about GCC.

Edit 2: added a for completeness.
Last edited on
Thanks for your quick answer, Catfish3!
Tested this on GCC 4.8.0. Works fine with a warning:

designated_initializer.cpp: In function 'int main()':
designated_initializer.cpp:11:14: warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]
     Test t = {.i = 1, .c = 'a'};
              ^
designated_initializer.cpp:11:21: warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]
     Test t = {.i = 1, .c = 'a'};
                     ^



1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

struct Test
{
    int i;
    char c;
};

int main()
{
    Test t = {.i = 1, .c = 'a'};

    std::clog << "t.i == " << t.i << '\t' << "t.c == " << t.c << '\n';
}
t.i == 1	t.c == a

Last edited on
Topic archived. No new replies allowed.