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?
Yes, thanks. The original wording could have been misinterpreted by beginning C programmers to develop a misconception along "Oh, static variables must be used with caution, so they must be bad in some way.
Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.
A structure declaration cannot be declared static, but its instancies can. You cannot have static members inside a structure because the members of a structure inherist the storage class of the containing struct. So if a structure is declared to be static all members are static even included substructures.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
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
A.a: 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With