In the following fragment I have a struct IndexError that I
return when the user made an error using my library. I have a function-like macro that casts a pointer to a IndexError*, and an enum, both called 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)
An example to how I would use this is:
size_t pos = 4;
int IndexPointer* error = NULL;
int status = array_remove_item(my_array, pos, &error);
Then I check the status. If it doesn't return SUCCESS, I would examine the error, because that should then point to a newly create error.
The implementation of one of the array functions might look like this:
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;
}
So my question is, at the return INDEX_ERROR;, will the INDEX_ERROR return the value from the enum, or will the preprocessor bite me because my naming is inconvenient?
return INDEX_ERROR; // is this the macro or the value from the errors enum?
It's the enumerator. It can't be the result of expanding the function-like macro, because it isn't followed immediately by a left paren ( token, as the preprocessor requires1.
It's slightly smelly, though. Different names for the macro and the enumerator will make the code clearer and self evident without needing to read the fine print of the language specification.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With