Tóm lại, không. Cách dễ nhất để thực hiện việc này sẽ giống như vậy (XIN LƯU Ý: điều này giả định rằng bạn không bao giờ có lỗi được gán cho số không/không):
//Should really be wrapping numerical definitions in parentheses.
#define FILE_NOT_FOUND (-2)
#define FILE_INVALID (-3)
#define INTERNAL_ERROR (-4)
typdef struct {
int errorCode;
const char* errorString;
} errorType;
const errorType[] = {
{FILE_NOT_FOUND, "FILE_NOT_FOUND" },
{FILE_INVALID, "FILE_INVALID" },
{INTERNAL_ERROR, "INTERNAL_ERROR" },
{NULL, "NULL" },
};
// Now we just need a function to perform a simple search
int errorIndex(int errorValue) {
int i;
bool found = false;
for(i=0; errorType[i] != NULL; i++) {
if(errorType[i].errorCode == errorValue) {
//Found the correct error index value
found = true;
break;
}
}
if(found) {
printf("Error number: %d (%s) found at index %d",errorType[i].errorCode, errorType[i].errorString, i);
} else {
printf("Invalid error code provided!");
}
if(found) {
return i;
} else {
return -1;
}
}
Tận hưởng!
Ngoài ra, nếu bạn muốn tiết kiệm gõ hơn nữa, bạn có thể sử dụng một macro tiền xử lý để làm cho nó thậm chí neater:
#define NEW_ERROR_TYPE(ERR) {ERR, #ERR}
const errorType[] = {
NEW_ERROR_TYPE(FILE_NOT_FOUND),
NEW_ERROR_TYPE(FILE_INVALID),
NEW_ERROR_TYPE(INTERNAL_ERROR),
NEW_ERROR_TYPE(NULL)
};
Bây giờ bạn chỉ cần gõ tên vĩ mô một lần, làm giảm nguy cơ lỗi chính tả.
Tôi nghĩ rằng không thể làm điều gì đó giống như trong C. Có thể bằng một số ngôn ngữ có OOP, như C# và phản xạ. Bộ xử lý trước – Jack
c thay thế tên. Bạn cần phản xạ. bạn có thể sử dụng Phản ánh CERN https://root.cern.ch/how/how-use-reflex https://stackoverflow.com/questions/359237/why-does-c-not-have-reflection – katta