经常在CU看各位大牛的文章,就目前自己的情况来说,他们的水平对我来说只能是可望而不可及。在此发文,权当巩固每天所学或者不经意间了解的东西,希望自己好好学习,进步快点。若哪里说的不对,请各位指出,以免误导别人,自己也好长点知识。
最近看linux内核和light sensor driver的源码,其中出现最多的应该就是结构体了。可是它的结构体初试化感觉和以前所看的不太一样(本科专业是电子,C语言只看过谭的那本),并没有花时间细抠“为什么在每个成员前面加一个‘.’?”之类的小问题。今天起床无事,突然想起来,便随便查了一下,现在整理下来供自己和正在入门的兄弟姐妹参考。
如light sensor driver里面有如下结构体:
- struct i2c_driver {
-
unsigned int class;
-
-
/* Notifies the driver that a new bus has appeared or is about to be
-
* removed. You should avoid using this if you can, it will probably
-
* be removed in a near future.
-
*/
-
int (*attach_adapter)(struct i2c_adapter *);
-
int (*detach_adapter)(struct i2c_adapter *);
-
-
/* Standard driver model interfaces */
-
int (*probe)(struct i2c_client *, const struct i2c_device_id *);
-
int (*remove)(struct i2c_client *);
-
-
/* driver model interfaces that don't relate to enumeration */
-
void (*shutdown)(struct i2c_client *);
-
int (*suspend)(struct i2c_client *, pm_message_t mesg);
-
int (*resume)(struct i2c_client *);
-
-
/* Alert callback, for example for the SMBus alert protocol.
-
* The format and meaning of the data value depends on the protocol.
-
* For the SMBus alert protocol, there is a single bit of data passed
-
* as the alert response's low bit ("event flag").
-
*/
-
void (*alert)(struct i2c_client *, unsigned int data);
-
-
/* a ioctl like command that can be used to perform specific functions
-
* with the device.
-
*/
-
int (*command)(struct i2c_client *client, unsigned int cmd, void *arg);
-
-
struct device_driver driver;
-
const struct i2c_device_id *id_table;
-
-
/* Device detection callback for automatic device creation */
-
int (*detect)(struct i2c_client *, struct i2c_board_info *);
-
const unsigned short *address_list;
-
struct list_head clients;
-
};
- struct i2c_driver al3000_driver = {
-
.driver = {
-
.name = AL3000_DRV_NAME,
-
.owner = THIS_MODULE,
-
},
-
.suspend = al3000_suspend,
-
.resume = al3000_resume,
-
.probe = al3000_probe,
-
.command = al3000_command,
-
.remove = __devexit_p(al3000_remove),
-
.id_table = al3000_id,
-
};
这种初始化写法就是所谓的C语言标记化结构初始化语法。
采用 .name = value这种形式,虽然没什么,但带来许多好处。举个小例子:
- struct student { //结构体名
-
char name[20];
-
char s;
-
int age;
- int score;
-
};
- struct student stu1 ={ //传统初始化
-
"x",'m',1,2
-
};
-
struct student stu1 ={ //上述标记式初始化
-
.score=2,
-
.age=1,
-
.name="x",
-
};
通俗总结一下优点:
1.顺序。(不理会结构体成员顺序,允许对结构成员进行重新排列。)
2.个数。(可以有选择性的初始化,不需要针对所有成员都进行初始化。)
3.性能。(将频繁被访问的成员放在相同的硬件缓存行上,将大大提高性能。)
4.扩展性好。(如增加字段时,避免了传统的那种大量修改。)
阅读(3617) | 评论(3) | 转发(0) |