Jules
Jules

Reputation: 14520

compiler error: "Expected ;" error in C struct

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?

Upvotes: 1

Views: 7324

Answers (2)

user529758
user529758

Reputation:

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?

Upvotes: 6

mah
mah

Reputation: 39847

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"
};

Upvotes: 2

Related Questions