首页 > 解决方案 > 让 C 预处理器评估最佳数组维度

问题描述

我相信这将是微不足道的,但我找不到答案。让我们考虑一下这个设置。

// suppose we often change the values of A,B,C
#define A 5
#define B 10
#define C 1
#define SIZE MAX(A+C,B)  //find the max somehow

int array[SIZE]

在我的程序中,我有很多参数和复杂的表达式。我试图找出一种方法来找到用于分配数组的最佳值,而无需每次都手动计算它。

标签: cc-preprocessor

解决方案


要找到和之间的最大值A + BC您可以在宏中使用三元表达式。

就像是:

#define A 5
#define B 10
#define C 1

#define MAX(A,B,C) ((((A) + (B)) > (C)) ? ((A) + (B)) : (C))
#define SIZE MAX(A,B,C) //15 the value of A + B
int array[SIZE];

如果要比较的值超过 2 个,则可以将它们链接起来以找到最大值。

假设您有一个D可以执行的宏:

//...
#define D 20

#define MAX(A,B,C,D) (((((A) + (B)) > C) && (((A) + (B)) > D)) ? ((A) + (B)) : (((C) > (D)) ? (C) : (D)))
#define SIZE MAX(A,B,C,D)  //20 the value of D

推荐阅读