Maxim Blinov
Maxim Blinov

Reputation: 946

MPLAB: XC8: Cannot assign struct variable

I am trying to compile the following code in MPLab v5.10 using XC8 for a PIC18.

The code is as follows:

struct vec2i {
    int x;
    int y;
};

void main(void) {
    static struct vec2i array[10];

    int i;
    for(i = 0; i < 10; ++i) {
        array[i] = {0, 0};
    }

    return;
}

This yields the following error:

newmain.c:11:20: error: expected expression
        array[i] = {0, 0};

This code compiles just fine on my native gcc compiler.

If I change the code to the following, the error goes away.

struct vec2i {
    int x;
    int y;
};

void main(void) {
    static struct vec2i array[10];

    int i;
    for(i = 0; i < 10; ++i) {
        // array[i] = {0, 0};
        array[i].x = 0;
        array[i].y = 0;
    }

    return;
}

I am using the free version of XC8, version 2.05. Is this a bug, or am I overlooking something with regards to the PIC architecture?

Upvotes: 1

Views: 1094

Answers (1)

Maxim Blinov
Maxim Blinov

Reputation: 946

Looks like I don't know C as well as I thought; The following post clarifies the problem I was facing: Struct initialization in C with error: expected expression

The corrected code reads as follows:

struct vec2i {
    int x;
    int y;
};

void main(void) {
    static struct vec2i array[10];

    int i;
    for(i = 0; i < 10; ++i) {
        array[i] = (struct vec2i){0, 0};
    }

    return;
}

Note that this kind of workaround is only available under C99. Selecting C90 from MPLAB verifies this (the above code fails to compile under C90).

As for the code working on my machine, I was actually using g++, which has support for extended initialier lists since c++11, which is enabled by default.

Upvotes: 1

Related Questions