cstructinitializationassignment-operatorcompound-literals

structs direct declaration in C


What is wrong with this code? I don't get why this isn't working.

struct point {
    int x;
    int y;
} eh;

void main() {
    eh = {1, 2};
    printf("%i", eh.x);
}

but this works fine

struct point {
    int x;
    int y;
} eh;

void main() {
    eh.x = 2;
    printf("%i", eh.x);
}

Solution

  • In C the assignment operator expects an expression but in this expression statement

    eh = {1, 2};
    

    the braced list is not an expression.

    The braced list can be used in initialization of an object. For example you could write

    struct point {
        int x;
        int y;
    } eh = { 1, 2 };
    

    or

    struct point {
        int x;
        int y;
    } eh = { .x = 1, .y = 2 };
    

    Or you could in main assign another object of the structure type using the compound literal like

    eh = ( struct point ){ 1, 2 };
    

    or

    eh = ( struct point ){ .x = 1, .y = 2 };
    

    The compound literal creates an unnamed object of the type struct point that is assigned to the object eh. One object of a structure type may be assigned to another object of the same structure type.

    You could also initialize the object eh with the compound literal

    struct point {
        int x;
        int y;
    } eh = ( struct point ){ .x = 1, .y = 2 };
    

    Pay attention to that according to the C Standard the function main without parameters shall be declared like

    int main( void )