如何内联分配 C 结构体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4777360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign a C struct inline?
提问by mindthief
typedef struct {
int hour;
int min;
int sec;
} counter_t;
And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like:
在代码中,我想在不显式初始化每个成员变量的情况下初始化此结构的实例。也就是说,我想做类似的事情:
counter_t counter;
counter = {10,30,47}; //doesn't work
for 10:30:47
10:30:47
rather than
而不是
counter.hour = 10;
counter.min = 30;
counter.sec = 47;
Don't recall syntax for this, and didn't immediately find a way to do this from Googling.
不要回忆这个语法,也没有立即从谷歌搜索中找到一种方法来做到这一点。
Thanks!
谢谢!
回答by Steve Jessop
Initialization:
初始化:
counter_t c = {10, 30, 47};
Assignment:
任务:
c = (counter_t){10, 30, 48};
The latter is called a "compound literal".
后者被称为“复合文字”。
回答by MuhsinFatih
For the sake of maintainability I prefer the list syntax WITH explicitly identified variables, as follows:
为了可维护性,我更喜欢使用显式标识变量的列表语法,如下所示:
counter_t counter = {.hour = 10, .min = 30, .sec = 47};
or for returning inline for example:
或用于返回内联例如:
return (struct counter_t){.hour = 10, .min = 30, .sec = 47};
I can imagine a scenario where one changes the order in which the variables are declared, and if you don't explicitly identify your variables you would have to go through all the code to fix the order of variables. This way it is cleaner and more readable I think
我可以想象一个场景,其中一个人改变了变量声明的顺序,如果你没有明确标识你的变量,你将不得不通过所有代码来修复变量的顺序。这样我认为它更干净,更具可读性
Side-note:
旁注:
As @AshleyDuncan and @M.M put, this feature was removed from ISO C++ after C99 https://stackoverflow.com/a/12122261/2770195, but is supported in gnu c++.
正如@AshleyDuncan 和@MM 所说,此功能在 C99 https://stackoverflow.com/a/12122261/2770195之后从 ISO C++ 中删除,但在 gnu c++ 中受支持。
So while you can do this just fine:
所以虽然你可以很好地做到这一点:
g++ -std=gnu++11 main.cpp -o main
This will throw an error if you try the example above:
如果您尝试上面的示例,这将引发错误:
# need an example. I was unable to find. Even clang++ supports it. If you know
# one, please suggest an edit
If you need to compile with a C++ compiler with support for ISO C++11 or later that does not recognize this gnu extension, you may have to use a class with a simple constructor:
如果您需要使用支持 ISO C++11 或更高版本的 C++ 编译器进行编译,但不能识别此 gnu 扩展,则可能必须使用具有简单构造函数的类:
// backup workaround
// not cool
class gnuFTW {
public:
int hour;
int min;
int sec;
gnuFTW(int hour, int min, int sec) {
this->hour = hour;
this->min = min;
this->sec = sec;
}
};
int main(int argc, const char * argv[]) {
gnuFTW counter = gnuFTW(10,30,47);
cout << counter.hour << endl;
return 0;
}