复合字面量和结构(C99)

作者:追风剑情 发布于:2020-3-10 16:27 分类:C

示例

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4.  
  5. #define MAXTITL 41
  6. #define MAXAUTL 31
  7.  
  8. struct book {
  9. char title[MAXTITL];
  10. char author[MAXAUTL];
  11. float value;
  12. };
  13.  
  14. struct rect { double x; double y; };
  15.  
  16. double rect_area(struct rect r);
  17. double rect_areap(struct rect * rp);
  18.  
  19. int main(int argc, char* argv[])
  20. {
  21. struct book readfirst;
  22. int score;
  23.  
  24. printf("Enter test score\n");
  25. scanf("%d", &score);
  26.  
  27. if (score >= 84)
  28. //用复合字面量为结构赋值
  29. readfirst = (struct book){ "Crime and Punishment",
  30. "Fyodor Dostoyevsky",
  31. 11.25 };
  32. else
  33. //用复合字面量为结构赋值
  34. readfirst = (struct book){ "Mr. Bouncy's Nice Hat",
  35. "Fred Winsome",
  36. 5.99};
  37.  
  38. printf("Your assigned reading:\n");
  39. printf("%s by %s: $%.2f\n", readfirst.title,
  40. readfirst.author, readfirst.value);
  41.  
  42. //将复合字面量作为函数参数传递
  43. double area;
  44. area = rect_area((struct rect) {10.5, 20.0});
  45.  
  46. double area1;
  47. area1 = rect_areap(&(struct rect) {10.5, 20.0});
  48. printf("area=%.2f, area1=%.2f\n", area, area1);
  49.  
  50. /*
  51. C99的复合字面量特性可用于结构和数组。如果只需要一个临时结构值,
  52. 复合字面量很好用。例如,可以使用复合字面量创建一个数组作为函数的参数
  53. 或赋给另一个结构。语法是把类型名放在圆括号中,后面紧跟一个用花括号括起来的
  54. 初始化列表。
  55.  
  56. 复合字面量在所有函数的外部,具有静态存储期;如果复合字面量在块中,
  57. 则具有自动存储期。复合字面量和普通初始化列表的语法规则相同。这意味着,
  58. 可以在复合字面量中使用指定初始化器。
  59. */
  60.  
  61. system("pause");
  62. return 0;
  63. }
  64.  
  65. double rect_area(struct rect r)
  66. {
  67. return r.x * r.y;
  68. }
  69.  
  70. double rect_areap(struct rect* rp)
  71. {
  72. return rp->x * rp->y;
  73. }

运行测试

11.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号