我有这样的数据结构:
struct foo {
int id;
int route;
int backup_route;
int current_route;
}
以及一个名为update()的函数,用于请求对其进行更改.
update(42, dont_care, dont_care, new_route);
这真的很长,如果我在结构中添加一些内容,我必须在每次调用更新(...)时添加'dont_care'.
我正在考虑将结构传递给它,但事先用'dont_care'填充结构比在函数调用中拼写它更加繁琐.我可以使用默认值dont care在某处创建结构,并在我将其声明为局部变量后设置我关心的字段吗?
struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);
将我希望表达的信息传递给更新功能的最优雅的方法是什么?
我希望其他一切都默认为-1("不关心"的密码)
是否可以为某些结构成员设置默认值?我尝试了以下但是,它会导致语法错误:
typedef struct
{
int flag = 3;
} MyStruct;
Run Code Online (Sandbox Code Playgroud)
错误:
$ gcc -o testIt test.c
test.c:7: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
test.c: In function ‘main’:
test.c:17: error: ‘struct <anonymous>’ has no member named ‘flag’
Run Code Online (Sandbox Code Playgroud) 昨天我发现了一些结构初始化代码,它让我循环.这是一个例子:
typedef struct { int first; int second; } TEST_STRUCT;
void testFunc() {
TEST_STRUCT test = {
second: 2,
first: 1
};
printf("test.first=%d test.second=%d\n", test.first, test.second);
}
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是(对我来说),这是输出:
-> testFunc
test.first=1 test.second=2
Run Code Online (Sandbox Code Playgroud)
如您所见,struct正确初始化.我不知道标签语句可以这样使用.我已经看到了其他几种进行结构初始化的方法,但我没有在任何在线C FAQ上找到任何这种结构初始化的例子.有人知道这是如何/为什么有效?