解決策の1つは、エラーコードのフィールドがint
で、エラーメッセージのフィールドがchar *
であるエラーメッセージ構造を作成することです。次に、エラーコードstruct
の配列をエラーコードとメッセージで初期化することができます。この方法では、新しいエラーメッセージでコードを簡単に更新できます。エラーメッセージの配列の最後のstruct
が、.msg
フィールドにヌルポインタを持つセンチネルとして使用されている場合、配列を反復処理する関数は、それに含まれる要素の数
ここは例です。 get_error()
機能は、アレイ上でループし、目的のエラーコードが発生したときにループから抜け出します。センチネル値に達して一致するものが見つからない場合は、「Unrecognized error code」というメッセージが返されます。新しいエラーメッセージが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;
}
OPはint
エラーコードを指定するだけでなく、enum
Sに言及しています。ここにはenum
を使用した変更があります。ここでenum
を使用する利点の1つは、読みやすさの向上です。欠点は、エラーメッセージが変更されたときにコードを2か所で変更する必要があることです。
#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いずれかのエラーコードは、1つのエラーメッセージにのみ対応し、コンパイル時には静的です。そして、私はアプローチの効率には関心がありません、私は実装の優雅さ、シンプルさ、拡張性、そして冗長性にもっと関心を持っています。 – vasia