如何初始化在C结构里面一个const变量? [英] How to initialize a const variable inside a struct in C?
本文介绍了如何初始化在C结构里面一个const变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写一个struct
I write a struct
struct Tree{
struct Node *root;
struct Node NIL_t;
struct Node * const NIL; //sentinel
}
我想
struct Node * const NIL = &NIL_t;
我不能在里面的结构初始化。
我使用MSVS。
I can't initialize it inside the struct. I'm using msvs.
我用C,不是C ++。
我知道我可以在C ++中使用初始化列表。
I use C, NOT C++. I know I can use initialization list in C++.
如何在C这样做?
推荐答案
如果您使用的是C99,便可以使用指定的初始值做到这一点:
If you are using C99, you can used designated initializers to do this:
struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
这仅适用于C99,虽然。我已经在GCC测试这和它似乎工作得很好。
This only works in C99, though. I've tested this on gcc and it seems to work just fine.
这篇关于如何初始化在C结构里面一个const变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文