在下面的片段中,我有一个 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/