tekknolagi
tekknolagi

Reputation: 11012

odd error in C; expecting something

I'm writing a small language in C, and it requires variable setting. I have a variable table set up, but I'm getting a strange error.

#define VAR_SIZE 100
typedef struct {
    const char *key;
    int value;
} variable;

variable Table[VAR_SIZE];
Table[0].key = NULL;
Table[0].value = 0;

When I run that, I get the following error:

stack.c:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token
stack.c:9: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘->’ token

What's going on?

Upvotes: 0

Views: 108

Answers (4)

Sylvain Defresne
Sylvain Defresne

Reputation: 44493

You can't have statement or expression at file scope. You can only have them at function scope. You need to change your last three lines to:

struct variable Table[VAR_SIZE] = { { NULL, 0 }, };

When using this syntax to initialize a structure or an array, any unspecified field is initialized to zero as if you did a memset(..., 0, sizeof(...)); on the remaining part of the structure / array. So you can add field to the structure, it will still compile.

By the way, in C, struct name live in their own namespace and you need to prefix them with the struct keyword.

Upvotes: 3

Wizz
Wizz

Reputation: 1267

You might have to initialize the 0 element of your array in a function. You can declare and define anything outside globally. But the latter two lines are assignments which can only occur in a function

example: (anything else just like you did above, except for the two lines :))

void test()
{
    Table[0].key = NULL;
    Table[0].value = 0;
}

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400204

You're trying to write code at global scope. You can't do that. You either need to give your global variable a static initializer, or initialize it at runtime inside of a function call.

An example of a static initializer:

variable Table[VAR_SIZE] = {
    {NULL, 0},  // index 0
    {NULL, 0},  // index 1
    // etc.
};

Initializing at runtime:

variable Table[VAR_SIZE];

void init_table(void) {
    Table[0].key = NULL;
    Table[0].value = 0;
    // etc.
}

int main(int argc, char **argv) {
    init_table();
    // rest of program
}

If you're compiling in C99 mode, you can also use a designated initializer:

// The following is valid C99, but invalid C89 and invalid C++
variable Table[VAR_SIZE] = {
    [0] = {   // initialize index 0
        .key = NULL,
        .value = 0
    },
    // etc.
};

Upvotes: 7

noelicus
noelicus

Reputation: 15055

You can only access it like that inside a function. To do it at global scope like that try:

variable Table[VAR_SIZE] = {{NULL,0},{NULL,0}};

if inside a function is OK then either do what you've already done or I'd go for a simple:

memset(Table, 0, sizeof(Table));

Upvotes: 0

Related Questions