한 가지 해결책은 오류 코드에 대한 int
필드와 오류 메시지에 대한 char *
필드를 포함하는 오류 메시지 구조를 만드는 것입니다. 그런 다음 오류 코드 struct
의 배열을 오류 코드 및 메시지와 함께 초기화 할 수 있습니다. 이 방법을 사용하면 코드를 새로운 오류 메시지로 쉽게 업데이트 할 수 있으며 .msg
필드에 오류 메시지 배열의 마지막 부분 인 struct
이 null 포인터가있는 센티널로 사용되는 경우 배열을 반복하는 함수는 알 필요가 없습니다 얼마나 많은 요소가 들어 있는지.
다음은 예입니다. get_error()
함수는 배열을 반복하며 원하는 오류 코드가 발생하면 루프를 벗어납니다. 센티널 값에 도달하여 일치하는 항목이 없으면 "인식 할 수없는 오류 코드"메시지가 반환됩니다. 새로운 오류 메시지가 error_codes[]
배열에 추가되므로 get_error()
함수를 수정할 필요가 없습니다.
#include <stdio.h>
struct Errors
{
const char *msg;
int code;
};
struct Errors error_codes[] = {
{ .code = 1, .msg = "input error" },
{ .code = 5, .msg = "format error" },
{ .code = 10, .msg = "allocation error" },
{ .msg = NULL }
};
const char * get_error(int err_code);
int main(void)
{
printf("Error: %s\n", get_error(1));
printf("Error: %s\n", get_error(5));
printf("Error: %s\n", get_error(10));
printf("Error: %s\n", get_error(-1));
return 0;
}
const char * get_error(int err_code)
{
struct Errors *current = error_codes;
const char *ret_msg = "Unrecognized error code";
while (current->msg) {
if (current->code == err_code) {
ret_msg = current->msg;
break;
}
++current;
}
return ret_msg;
}
영업 이익은 int
오류 코드를 지정뿐만 아니라 enum
의 언급했다. 다음은 enum
을 사용한 수정입니다. 여기에 enum
을 사용하면 얻을 수있는 장점 중 하나는 판독 가능성이 향상된다는 것입니다. 단점은 오류 메시지가 변경 될 때 코드를 두 곳에서 수정해야한다는 것입니다.
#include <stdio.h>
/* Modify both the Error_Codes enum and the following error_codes[] array
when adding new error messages. */
enum Error_Codes {
ERRINPUT = 1,
ERRFORMAT = 5,
ERRALLOC = 10
};
struct Errors
{
const char *msg;
enum Error_Codes code;
};
struct Errors error_codes[] = {
{ .code = ERRINPUT, .msg = "input error" },
{ .code = ERRFORMAT, .msg = "format error" },
{ .code = ERRALLOC, .msg = "allocation error" },
{ .msg = NULL }
};
const char * get_error(enum Error_Codes err_code);
int main(void)
{
printf("Error: %s\n", get_error(ERRINPUT));
printf("Error: %s\n", get_error(ERRFORMAT));
printf("Error: %s\n", get_error(ERRALLOC));
printf("Error: %s\n", get_error(-1));
return 0;
}
const char * get_error(enum Error_Codes err_code)
{
struct Errors *current = error_codes;
const char *ret_msg = "Unrecognized error code";
while (current->msg) {
if (current->code == err_code) {
ret_msg = current->msg;
break;
}
++current;
}
return ret_msg;
}
프로그램 출력 :
Error: input error
Error: format error
Error: allocation error
Error: Unrecognized error code
당신은 가능한 한 효율적으로 스위치를 소문자로 컴파일러를 신뢰할 수 있습니다. 네, 이것이 최선의 방법입니다. –
매크로는 컴파일 할 때 평가되기 때문에 매크로로 처리 할 수 없습니다. 런타임 중에 오류 코드가 생성되었다고 확신합니다. –
@AjayBrahmakshatriya 하나의 오류 코드는 하나의 오류 메시지에만 해당하며 컴파일시 정적입니다. 그리고 접근 방식의 효율성에 관심이 없기 때문에 구현의 우아함, 단순성, 확장 성 및 자세한 정보에 더 관심이 있습니다. – vasia