我正在嘗試撰寫一個類似于宏的斷言來檢查運行時錯誤。在最底部,您可以找到我為該宏提供的內容,并且有些事情與我期望的不一樣。
首先沒有的是功能評估。假設someFuntion()回傳一個整數,expr = (someFunction() > 0)
在這種情況下,即使someFunction()大于零,運算式也會失敗。
其次,我希望能夠執行多個操作。例如,如果我通過 2 個動作,我希望執行兩個動作。我希望能夠通過 execute_action_before_exit =(someFunction2(), someFucntion3())
并且它應該在退出之前執行所有功能。我應該怎么做才能做到這一點?還是不可能?
我的代碼:
#ifndef RT_ASSERT_H
#define RT_ASSERT_H
#include <stdlib.h>
#include <stdio.h>
#define rt_assert(expr, file, str, execute_action_before_exit) \
((void) sizeof ((expr) ? 1 : 0), __extension__ ({ \
if (!expr) { \
fprintf(file, "In file %s:%d, Error: %s\n",__FILE__, __LINE__, str); \
execute_action_before_exit; \
fclose(file); \
exit(EXIT_FAILURE); \
} \
}))
當前宏的使用
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "runtime_assert.h"
void someFunction(void) {
// does some cleaning action or any action
}
void someFunction1(void) {
// does some cleaning action or any action
}
int main (void) {
FILE *abort_msg = fopen("exit_msg.txt", "w ");
if (!abort_msg) {
printf("Failed to create/open exit_msg.txt\n");
getchar();
exit(EXIT_FAILURE);
}
FILE *foo = fopen("FOO.txt", "r");
rt_assert((foo), abort_msg, "Failed of open file -->possibly missing<--", (someFunction()));
fclose(abort_msg);
return EXIT_SUCCESS;
我想如何修改使用
rt_assert( \
(foo), \
abort_msg, "Failed of open file -->possibly missing<--", \
(someFunction(),someFunction1()) \
);
uj5u.com熱心網友回復:
#define rt_assert(expr, file, str, ...)\
((void) sizeof ((expr) ? 1 : 0), __extension__ ({\
if (!(expr)) {\
fprintf((file), "In file %s:%d, Error: %s\n",__FILE__, __LINE__, (str));\
__VA_ARGS__;\
fclose(file);\
exit(EXIT_FAILURE);\
}\
}))
我在這里做了兩個改變:
(1) 用來!(expr)代替!expr. 這解決了您遇到的第一個問題,即傳入的運算式被錯誤地評估。請記住,宏基本上只是復制粘貼,所以當你這樣做時rt_assert( x() > 0 , rest of the arguments),它會被“粘貼”到 if 陳述句中if (!x() > 0) ...,不會像你期望的那樣被評估。您想要的是if (!(x() > 0)) ...,現在已正確處理。我對其他引數做了同樣的事情。
(2) 我已將宏更改為可變引數,因此您可以向它傳遞任意數量的引數。其語法是...在宣告宏時__VA_ARGS__使用可變引數。(搜索“可變引數宏”以在此處找到更多資訊。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518362.html
標籤:C错误处理
下一篇:使用結構和函式列印選單
