What is the best way to accomplish the following in C?
#include <stdio.h> struct A { int x; }; struct A createA(int x) { struct A a; a.x = x; return a; } struct A a = createA(42); int main(int argc, char** argv) { printf("%d\n", a.x); return 0; }
When I try to compile the above code, the compiler reports the following error:
"initializer element is not constant"
The bad line is this one:
struct A a = createA(42);
Can someone explain what is wrong? I'm not very experienced in C. Thanks!
You can define structure globally and locally. If the structure is global then it must be placed above all the functions, so that any function can use it. On the other hand, if a structure is defined inside a function then only that function can use the structure.
Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).
To declare a structure globally, place it BEFORE int main(void). The structure variables can then be defined locally in main, for example.
You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.
struct A a = { .x = 42 };
More members:
struct Y { int r; int s; int t; }; struct Y y = { .r = 1, .s = 2, .t = 3 };
You could also do
struct Y y = { 1, 2, 3 };
The same thing works for unions, and you don't have to include all of the members or even put them in the correct order.
Why not use static initialization?
struct A a = { 42 };
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