How to initialize a const variable inside a struct in C?
I write a struct
struct Tree{
struct Node *root;
struct Node NIL_t;
struct Node * const NIL; //sentinel
}
I want
struct Node * const NIL = &NIL_t;
I can't initialize it in开发者_StackOverflowside the struct. I'm using msvs.
I use C, NOT C++. I know I can use initialization list in C++.
How to do so in C?
If you are using C99, you can used designated initializers to do this:
struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
This only works in C99, though. I've tested this on gcc and it seems to work just fine.
For those seeking a simple example, here it goes:
#include <stdio.h>
typedef struct {
const int a;
const int b;
} my_t;
int main() {
my_t s = { .a = 10, .b = 20 };
printf("{ a: %d, b: %d }", s.a, s.b);
}
Produces the following output:
{ a: 10, b: 20 }
A structure defines a data template but has no data itself. Since it has no data, there's no way to initialize it.
On the other hand, if you want to declare an instance, you can initialize that.
struct Tree t = { NULL, NULL, NULL };
Maybe something like this will suffice?
struct {
struct Node * const NIL;
struct Node *root;
struct Node NIL_t;
} Tree = {&Tree.NIL_t};
精彩评论