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

标签 c function struct variable-assignment standard-library

假设我有以下结构:

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/

相关文章:

c - 为什么这个 C 程序不提取转义的反斜杠?

c - ptrace 在 64 位中不工作

swift - 看起来返回键对我的方法不起作用

将结构成员复制到数组

arrays - 将结构转换为字节数组并返回 Rust

c - 在 C 中,如何在不关闭/关闭套接字的情况下写入数据后指示 EOF?

python - 读取在 C 中使用 Python struct 编写的二进制数据

c# - 如何从 C# 程序运行 bat 文件?

javascript - 单击按钮时播放音频(无循环)

c - 如何设置将用户输入拆分为多个部分并拆分那些较小部分的 C 函数?