C 结构中的默认值 [英] Default values in a C Struct

查看:15
本文介绍了C 结构中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据结构:

struct foo {
    int id;
    int route;
    int backup_route;
    int current_route;
}

还有一个名为 update() 的函数,用于请求对其进行更改.

and a function called update() that is used to request changes in it.

update(42, dont_care, dont_care, new_route);

这真的很长,如果我在结构中添加一些东西,我必须在每次调用 update(...) 时添加一个dont_care".

this is really long and if I add something to the structure I have to add a 'dont_care' to EVERY call to update( ... ).

我正在考虑将它传递给一个结构,但事先用'dont_care'填充结构比在函数调用中拼写出来更乏味.我可以在某处创建默认值不关心的结构,并在我将其声明为局部变量后设置我关心的字段吗?

I am thinking about passing it a struct instead but filling in the struct with 'dont_care' beforehand is even more tedious than just spelling it out in the function call. Can I create the struct somewhere with default values of dont care and just set the fields I care about after I declare it as a local variable?

struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);

将我希望表达的信息传递给更新函数的最优雅的方式是什么?

What is the most elegant way to pass just the information I wish to express to the update function?

我希望其他所有内容都默认为 -1('dont care' 的密码)

and I want everything else to default to -1 (the secret code for 'dont care')

推荐答案

虽然宏和/或函数(如前所述)可以工作(并且可能有其他积极影响(即调试挂钩)),但它们比需要的复杂.最简单也可能是最优雅的解决方案是只定义一个用于变量初始化的常量:

While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:

const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
    dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);

这段代码几乎没有理解间接的精神开销,并且非常清楚bar中的哪些字段是您明确设置的,而(安全地)忽略了那些您没有设置的字段.

This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.

这篇关于C 结构中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆