在 C 的公共 API 函数中使用枚举参数是个好主意吗? [英] Is it a good idea to use an enum parameter in public API function in C?

查看:28
本文介绍了在 C 的公共 API 函数中使用枚举参数是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个 C API,它必须提供一种方法来设置一些双值选项.为了识别选项,我使用以下枚举:

I am designing a C API which among other things has to provide a way to set some double-valued options. To identify the options I use the following enum:

typedef enum
{
    OptionA,
    OptionB,
    ...
} Option;

在公共 API 函数中使用 Option 作为参数类型是否一个好主意:

Is it a good idea to use Option as a parameter type in a public API function:

int set_option(Option opt, double value);

或者用 int 代替更好:

int set_option(int opt, double value);

考虑到我将来可能需要添加更多选项?

considering that I may need to add more options in the future?

是否有任何现有 API 的优秀示例来演示这两种方法?

Also are there any good examples of existing APIs that demonstrate either approach?

推荐答案

通过使用 enum,您可以有效地帮助函数的用户了解哪些有效值可用.当然,缺点是每当添加新选项时,您都需要修改标题,因此用户可能需要重新编译他的代码,而如果它是 int,他可能不必这样做.

By using an enum you are effectively helping the user of your function to know what valid values are available. Of course the drawback is that whenever a new option is added you will need to modify the header and thus the user may need to recompile his code whereas if it is an int he may not have to do that.

这篇关于在 C 的公共 API 函数中使用枚举参数是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆