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

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

问题描述

我有一个数据结构是这样的:

I have a data structure like this:


    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);

这是很长的,如果我添加了一些结构我有一个'DONT_CARE添加到每个调用来更新(...)。


我想传递一个结构,而不是填补,但在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( ... ).

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);

什么是传递只是我想前preSS的更新功能的信息最优雅的方式?

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

和我想一切默认为-1(秘密code为'不在乎')

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);

这code几乎没有精神上的开销理解间接,这是很清楚哪些字段在酒吧,您精确设置,而(安然)忽略了那些你不设置。

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

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

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