假设我有以下结构:
struct cube {
int height;
int length;
int width;
};
我需要创建一个库,允许用户将值输入到结构中,然后将其传递给一个函数,该函数将确定用户是想要area
还是volume
来自提供的值。
例如:
int main() {
struct cube shape;
shape.height = 2;
shape.width = 3;
printf("Area: %d", calculate(shape)); // Prints 6
shape.length = 4;
printf("Volume: %d", calculate(shape)); // Prints 24
return 0;
}
int calculate(struct cube nums) {
if (is_present(nums.height, nums) && is_present(nums.width, nums)) {
return nums.height * nums.width;
}
else if (is_present(nums.height, nums) && is_present(nums.width, nums) && is_present(nums.length, nums)) {
return nums.height * nums.width * nums.length;
}
else {
return -1; // Error
}
}
如果我可以使用一个函数(比如我刚刚编写的 is_present()
)来确定是否为结构的成员提供了值,这应该可行。
是否有这样的功能,如果没有,如何实现?
最佳答案
您应该将字段初始化为可能值范围之外的内容。例如,对于此类为正数的维度,负值可以充当“未分配”值。
此外,我重新排序了您的 if
语句:检查所有字段的语句应该放在第一个。
这是一个例子:
#include <stdio.h>
#define NOT_PRESENT -1
#define is_present(x) ((x) != NOT_PRESENT)
struct cube {
int height;
int length;
int width;
};
int calculate(struct cube);
int main() {
struct cube shape = {
.height = NOT_PRESENT,
.length = NOT_PRESENT,
.width = NOT_PRESENT,
};
shape.height = 2;
shape.width = 3;
printf("Area: %d\n", calculate(shape)); // Prints 6
shape.length = 4;
printf("Volume: %d\n", calculate(shape)); // Prints 24
return 0;
}
int calculate(struct cube nums) {
if (is_present(nums.height) && is_present(nums.width) && is_present(nums.length)) {
return nums.height * nums.width * nums.length;
} else if (is_present(nums.height) && is_present(nums.width)) {
return nums.height * nums.width;
} else {
return -1; // Error
}
}
关于c - 如何确定结构的成员是否已设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57676531/