1

I'm trying to add a struct to my program using this syntax:

struct foo {
    char bar[] = "baz";
    char qux[] = "abc";
    /* and so on */
};

For some reason, I get an error on each variable declaration within the struct saying that I have to add semicolons, and seems to fall into a kind of loop with this. The suggested syntax would be something like

struct foo {
    char bar[]; =; ;;;;;;/* infinite semicolons */"baz";
}

This is the first time I've had this kind of error; am I really doing something wrong, or is this just an issue with the compiler itself?

3
  • You don't even know the syntax for declaring a struct (nor the difference between a compiler and an IDE), and you accuse the creators of Xcode of writing such an enormous bug? I think the word of the day for you is humillity. Commented Jun 21, 2013 at 17:00
  • I'm not accusing the programmers behind Xcode of anything. I know that software bugs happen, and I'm new to structs. I thought they could follow syntax similar to that of unions. Commented Jun 21, 2013 at 17:03
  • 2
    @user2129150 they do follow syntax similar to that of a union… you cannot do what you tried as a union either. Commented Jun 21, 2013 at 17:05

2 Answers 2

6

This has nothing to do with Xcode. At all.

You're getting a compiler error because you can't initialize structs like this.

The struct type definition is about types only. Assigning values to members at this point makes no sense. Maybe you meant

struct foo {
    char *bar;
    char *baz;
};

struct foo x = { "quirk", "foobar" };

instead?

Sign up to request clarification or add additional context in comments.

1 Comment

Initializing struct members does make sense; in fact, C++ permits it as of the 2011 ISO standard, probably by creating an implicit constructor. The semantics seem clear enough; every created object of the type would have those members initialized to the specified values by default. C just doesn't happen to permit it.
2

You are doing something wrong. You cannot assign values to the members of the struct… you're in the middle of defining the data type, not an instance of it.

This will give you your struct definition and then directly declare a variable (with initialization) of its type:

struct foo {
    char *bar;
    char *qux;
} variable_name = {
    "baz", "abc"
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.