时间:2023-02-20 04:42:02 | 来源:建站知识
时间:2023-02-20 04:42:02 来源:建站知识
C语言使用连接符##来优雅的创建多个结构体:#include <stdio.h>typedef struct { char name[20]; int age; int score; int grade;}Student;Student A = { "petter", 8, 90, 1,};Student * studentList[] = { &A,};int main(void){ for(int i=0;i<sizeof(studentList)/sizeof(Student *);i++){ printf("name = %s,age = %d,score = %d,grade = %d/r/n", / studentList[i]->name,studentList[i]->age,studentList[i]->score,studentList[i]->grade); } return 0;}
现在人数变多了,增加了三个人的数据信息,分别是一年级学生lucy还有两个二年级学生nancy和matt。#include <stdio.h>typedef struct { char name[20]; int age; int score; int grade;} Student;Student petter = { "petter", 8, 90, 1,};Student lucy = { "lucy", 8, 100, 1,};Student nancy = { "nancy", 9, 60, 2,};Student matt = { "matt", 9, 55, 2};Student *studentList[] = {&petter, &lucy, &nancy, &matt};int main(void) { for (int i = 0; i < sizeof(studentList) / sizeof(Student *); i++) { printf("name = %s,age = %d,score = %d,grade = %d/r/n", studentList[i]->name, studentList[i]->age, studentList[i]->score, studentList[i]->grade); } return 0;}
这个时候我们发现,四个学生,声明结构体的代码就很长了,不好看。如果来了更多的学生数据,那岂不是代码越来越长了吗?多一个学生数据会多6行。那么如何用一个更好的写法来优雅的解决这个问题呢?#include <stdio.h>int algorithm_add_op(int num1, int num2) { return num1+num2;}int algorithm_sub_op(int num1, int num2) { return num1 - num2;}#define ALGORITHM(name, num1, num2) / algorithm_##name##_op(num1, num2)int main() { printf("%d/n", ALGORITHM(add, 1, 2)); printf("%d/n", ALGORITHM(sub, 1, 2)); return 0;}
看上述代码 ALOGORITHM函数把输入的子串和algorithm和_op连接起来,使得编译器调度到对应二点操作函数#include <stdio.h>typedef struct { char name[20]; int age; int score; int grade;}Student;#define DECLARE_GRADE_1_AGE_8_STUDENT(name,score) / static const Student Student_##name = { / #name,8,score,1 / };#define DECLARE_GRADE_2_AGE_9_STUDENT(name,score) / static const Student Student_##name = { / #name,9,score,2 / };#define DECLARE_STUDENT(name,age,score,grade) / static const Student Student_##name = { / #name,age,score,grade / };DECLARE_GRADE_1_AGE_8_STUDENT(petter,90)DECLARE_GRADE_1_AGE_8_STUDENT(lucy,100)DECLARE_GRADE_2_AGE_9_STUDENT(nancy,60)DECLARE_GRADE_2_AGE_9_STUDENT(matt,55)Student const * studentList[] = { &Student_petter, &Student_lucy, &Student_nancy, &Student_matt};int main(void){ for(int i=0;i<sizeof(studentList)/sizeof(Student *);i++){ printf("name = %s,age = %d,score = %d,grade = %d/r/n", / studentList[i]->name,studentList[i]->age,studentList[i]->score,studentList[i]->grade); } return 0;}
上述代码我们定义了一个宏,这个宏有两个输入参数,作用是创建一个结构体变量,通过name来给这个结构体变量命名,结构体名称使用到了连接符。关键词:创建,结构,连接,使用,语言