简体   繁体   中英

Static struct initialization in C

I have a struct type as shown below:

typedef struct position{
    float X;
    float Y;
    float Z;
    float A;
} position;

typedef struct move{
    position initial_position;
    double feedrate;
    long speed;
    int g_code;
} move;

I am trying to statically initialize it, but I have not found a way to do it. Is this possible?

It should work like this:

move x = { { 1, 2, 3, 4}, 5.8, 1000, 21 };

The brace initializers for structs and arrays can be nested.

C doesn't have a notion of a static-member object of a struct/class like C++ ... in C, the static keyword on declarations of structures and functions is simply used for defining that object to be only visible to the current code module during compilation. So your current code attempts using the static keyword won't work. Additionally you can't initialize structure data-elements at the point of declaration like you've done. Instead, you could do the following using designated initializers :

static struct {
    position initial_position;
    double feedrate;
    long speed;
    int g_code;
} move = { .initial_position.X = 1.2,
           .initial_position.Y = 1.3,
           .initial_position.Z = 2.4,
           .initial_position.A = 5.6,
           .feedrate = 3.4, 
           .speed = 12, 
           .g_code = 100};

Of course initializing an anonymous structure like this would not allow you to create more than one version of the structure type without specifically typing another version, but if that's all you were wanting, then it should do the job.

#include <stdio.h>

struct A {
    int a;
    int b;
};

struct B {
    struct A a;
    int b;
};

static struct B a = {{5,3}, 2};

int main(int argc, char **argv) {
    printf("A.a: %d\n", a.a.a);
    return 0;
}

result:

$ ./test

Aa: 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM