我正在嘗試為我的專案創建一個簡單的單元測驗庫。我可以讓大多數事情正常作業,但現在我正在嘗試添加一些功能:列印運算式/輸入。
如果我通過實際值 (1, 2.456, false) 傳遞引數,它會起作用,但是如果我傳遞一個函式引數,我會列印出函式字串。
這是我的代碼解釋了這個問題我不是 100% 確定 STR(x) 宏在做什么,從網上某處復制它...
代碼實際上有效(LHS 和 RHS 的評估)只是列印無效,如下所示。
#include <stdio.h>
#define STR(x) #x
#define TEST_COMPARE_EQ(TestName, LHS, RHS) \
do { \
if ((LHS) != (RHS)) { \
printf("[Test: %s] --- Failed at line %d in file %s\n", TestName, __LINE__, __FILE__); \
printf("\Got value %s\n", STR(LHS)); \
printf("\Expected value %s\n", STR(RHS)); \
} \
else { \
printf("[Test: %s] --- Passed\n", TestName); \
}\
} while (0)
// Calling code example
// This works, prints:
// Got value 123
// Expected value 124
TEST_COMPARE_EQ("PrintingWorks", 123, 124);
// This however does not work.
// It prints
// Got value my_fn_that_returns_false
// Expected value true
// How can I get it to print the return value of my_fn_that_returns_false, and not
// the actual function name?
TEST_COMPARE_EQ("PrintingDoesNotWork", my_fn_that_returns_false(), true);
uj5u.com熱心網友回復:
STR(x) 宏在做什么,
它按原樣使用代碼并"在前后添加。STR(anything)就是"anything",就是這樣。
我怎樣才能讓它列印回傳值
你必須列印它。
printf("Got value %d\n", LHS);
不,C 中沒有模板。很難在 C 中撰寫型別泛型函式。您必須分別處理每種可能的型別 - 如TEST_COMPARE_EQ_INT TEST_COMPARE_EQ_FLOAT等。如需靈感,請查看Unity C 單元測驗庫。
以型別通用的方式撰寫它聽起來像是在 C 中的一個很好的挑戰。 它看起來基本上如下所示:
void test_eq_int(int a, const char *astr, int b, const char *btr) {
if (a != b) {
printf("%s = %s -> %d != %s\n", astr, bstr, a, b);
}
}
void test_eq_long(....) { .... }
void test_eq_some_other_type(...) { .... }
// etc. for each possible type
#define TEST_COMPARE_EQ(msg, a, b) \
_Generic(a, \
int: test_eq_int, \
long: test_eq_long, \
/* etc. for each type */ \
)(msg, a, #a, b, #b);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/356307.html
標籤:C
上一篇:使用緩沖區洗掉字串中的重復項
下一篇:零大小陣列未在結構內對齊
