-3

Here is a code snippet:

typedef struct foo {
    int i;
    int o;
} foo;

int main() {
    foo bar2 = {
        .i = 42;
        .o= 24;
    };
    foo bar1;
    bar1.i = 42;
    bar1.o = 24;
}

I am trying to initialize the variable bar2 within the declaration, but it didn't work. But the initialization of the struct bar1 works pretty fine. Can Anybody tell me why the initialization of foo2 gives a SyntaxError?

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Lui
  • 159
  • 9

1 Answers1

4

The initializer elements must be separated with a comma, not a semicolon, However while C (since C99) supports designated initializers, standard C++ does not support it. See this question.

You can do:

foo bar2 = { 42, 24 };

Some C++ compilers might support such a designated initializer list, which comes from C, as an extension - in which case the syntax would be:

foo bar2 = {.i = 42, .o= 24};
Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506
  • Ok, thanks alot, so there where two faults: First: I mistyped and seperated by comma instead of semicolon. Second: I'm used to C and not C++. But in this case I had to use C++ and I didn't know that this initialization is not supported. Thank You! – Lui Feb 12 '15 at 09:51