Home > Back-end >  structs direct declaration in C
structs direct declaration in C

Time:12-07

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

CodePudding user response:

That kind of syntax might work in some other languages, but in C you should write:

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

The expression on the right hand side is called a compound literal.

CodePudding user response:

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 )

CodePudding user response:

This would also work:

#include <stdio.h>

struct point {
    int x;
    int y;
};

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

Note that I removed some things around, added the stdio.h include and fixed the main function type and arguments.

  • Related