Thorpe

导航

 

结构中使用复合字面量,

我们有一个结构:

1 struct date
2 {
3     int year;
4     int month;
5     int day;
6 };

一般给这个结构赋值会是:

1 struct date today = {2015,7,28};
2 // 或者是
3 // struct date today = 
4 //     {.day = 28, .year = 2015, .month = 7};

 

而用复合字面量的方式:

1 today = (struct date){2015, 7, 28};
2 //或是
3 //today = (struct date){.month = 7, .day = 28, .year = 2015};

 

这样看起来似乎没什么卵用,但是把复合字面量运用到程序当中去会发现很是方便:

// 普通运用
// if (today != 30){
//      tomorrow.day = today.day + 1;
//      tomorrow.month = today.month;
//      tomorrow.year = today.year;    

// 复合字面量运用
if (today.day != 60)
    tomorrow = (struct date){today.month, today.day + 1, today.year};

同样的运行结果,运用复合字面量会直观很多,也更为方便。

posted on 2015-07-28 17:17  Thorpe  阅读(109)  评论(0)    收藏  举报