Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can members in a structure be initialized to a value?

I was just wondering if a variable declared and defined inside a structure can be initialized to a certain value, was planning on using function pointers to mimic the classes in OOP.

Example COde:

typedef struct{
int x;
int (*manipulateX)(int) = &manipulateX;
}x = {0};

void main()
{
    getch();
}

int manipulateX(int x)
{
    x = x + 1;
return x;
}
like image 554
lemoncodes Avatar asked Jan 14 '23 14:01

lemoncodes


1 Answers

Starting with C99, you can use designated initializers to set fields of structures to values, as follows:

struct MyStruct {
    int x;
    float f;
};

void test() {
    struct MyStruct s = {.x=123, .f=456.789};
}
like image 98
Sergey Kalinichenko Avatar answered Jan 30 '23 07:01

Sergey Kalinichenko