代码超25行触发norminette报错,求精简C语言set_default函数方案
精简FDF的set_default函数以符合Norminette规范
通过结构体数组映射阈值与对应配置参数的方式,可以彻底消除冗余的if-else分支,大幅减少代码行数,同时保持逻辑清晰:
步骤1:定义配置映射结构体
在文件顶部(或对应的头文件中)添加结构体定义,用来存储不同map_size阈值对应的参数:
#include <limits.h> // 用于INT_MAX typedef struct s_config { int max_size; int window_x; int window_y; int zoom; int depth; } t_config;
步骤2:修改set_default函数
用静态结构体数组存储所有配置规则,通过循环匹配对应的区间后直接赋值:
void set_default(t_fdf *data, char **av) { static const t_config configs[] = { {500, 960, 540, 30, 2}, {3000, 1280, 720, 20, 15}, {5000, 1366, 768, 20, 10}, {10000, 1600, 900, 10, 5}, {INT_MAX, 1720, 900, 5, 4} }; size_t i = 0; read_map(data, av[1]); while (data->map_size > configs[i].max_size) i++; data->window_x = configs[i].window_x; data->window_y = configs[i].window_y; data->zoom = configs[i].zoom; data->depth = configs[i].depth; }
可选:提取匹配逻辑为辅助函数
如果希望进一步拆分逻辑,可以把区间匹配的代码抽成静态辅助函数(参数数量符合要求):
static size_t get_config_idx(int map_size) { static const t_config configs[] = { {500, 960, 540, 30, 2}, {3000, 1280, 720, 20, 15}, {5000, 1366, 768, 20, 10}, {10000, 1600, 900, 10, 5}, {INT_MAX, 1720, 900, 5, 4} }; size_t i = 0; while (map_size > configs[i].max_size) i++; return i; } void set_default(t_fdf *data, char **av) { static const t_config configs[] = { {500, 960, 540, 30, 2}, {3000, 1280, 720, 20, 15}, {5000, 1366, 768, 20, 10}, {10000, 1600, 900, 10, 5}, {INT_MAX, 1720, 900, 5, 4} }; size_t idx = get_config_idx(data->map_size); read_map(data, av[1]); data->window_x = configs[idx].window_x; data->window_y = configs[idx].window_y; data->zoom = configs[idx].zoom; data->depth = configs[idx].depth; }
这种方式不仅能将代码行数控制在25行以内,还能让后续调整配置参数变得更简单——只需修改结构体数组中的值即可,无需修改分支逻辑。
内容的提问来源于stack exchange,提问作者Yusuf Ugurlu
相关产品推荐
相关产品推荐

