c - 具有相同名称的类似函数的宏和枚举器

标签 c macros c-preprocessor

在下面的片段中,我有一个 struct IndexError,我 当用户使用我的库出错时返回。我有一个类似于函数的宏,它将一个指针转换为 IndexError* 和一个枚举,两者都称为 INDEX_ERROR

enum errors {
    SUCCESS,
    INVALID_ARGUMENT,
    INDEX_ERROR
};

struct Error {
    char error_buff[BUFSIZ];
};

typedef struct Error Error;

struct IndexError {
    Error  parent;
    size_t invalid_index;
    // etc.
};

typedef struct IndexError IndexError;


#define INDEX_ERROR(obj) ((IndexError*) obj)

我将如何使用它的示例是:

size_t pos = 4;
int IndexPointer* error = NULL;
int status = array_remove_item(my_array, pos, &error);

然后我检查状态。如果它没有返回 SUCCESS,我会检查错误,因为那应该指向一个新创建的错误。

其中一个数组函数的实现可能如下所示:

int array_remove_item(Array* array, size_t pos, Error** error_out)
{
    Error* error = NULL;
    if(pos >= array->size) {
        index_error_create(INDEX_ERROR(&error), pos); // use casting macro.
        *error_out = error;
        return INDEX_ERROR; // is this the macro or the value from the errors enum?
    }
    priv_array_remove_item(array, pos);
    return SUCCESS;
}

所以我的问题是,在 return INDEX_ERROR; 处,INDEX_ERROR 会从枚举中返回值,还是预处理器会因为我的命名不方便而咬我?

最佳答案

return INDEX_ERROR; // is this the macro or the value from the errors enum?

这是枚举器。它不可能是扩展类函数宏的结果,因为它后面没有紧跟左括号 ( 标记,因为预处理器需要1

虽然有点臭。宏和枚举器的不同名称将使代码更清晰和不言自明,而无需阅读语言规范的细则。


<子> 1 - n1570 6.10.3p10 "Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition"

关于c - 具有相同名称的类似函数的宏和枚举器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55158936/

相关文章:

c - 使用双指针函数 C 语言访问二维数组

c - 为什么整数提升的结果不同?

vim - 如何停止运行 Vim 宏

c - 你如何测试两个#defines是否与C预处理器相同

c - 将大量线程固定到单个 CPU 会导致所有内核的利用率激增

macros - eval 宏未绑定(bind)变量(CHICKEN 方案)

c++ - 使用预处理器生成具有多个参数的显式实例化

c# - 是否有检测 ASP.NET 的指令?

objective-c - iPhone项目常数

c - 将全局结构变量存储在 C 中的另一个全局结构中