如何在C中的结构内初始化const变量? [英] How to initialize a const variable inside a struct in C?
本文介绍了如何在C中的结构内初始化const变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个结构
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 中做到这一点?
How to do so in 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屋!
查看全文