如何确定结构的成员是否已设置?

How to work out if a member of a struct was set or not?

假设我有以下结构:

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())来计算是否为结构成员提供了值,这应该可行。

是否有这样的功能,如果没有,如何实现?

首先您必须明确定义“a value was given”对您的域意味着什么。成员初始化为0表示没有赋值?

一个简单的解决方案是用 0(例如)初始化您的结构,然后将每个成员与它进行比较。示例:

struct cube shape = {0};
shape.width = 3;
if (shape.width != 0)
    printf("width was set");

或更简单:

struct cube shape = {2,0,3};
if (shape.width != 0)
    printf("width was set");

您应该将字段初始化为可能值范围之外的内容。例如,对于此类为正数的维度,负值可以充当 "not assigned" 值。

此外,我重新排序了您的 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
    }
}