json-tutorial icon indicating copy to clipboard operation
json-tutorial copied to clipboard

在宏里面使用函数时,函数会被调用两次

Open 4yannf opened this issue 4 years ago • 4 comments

#define EXPECT_EQ_BASE(equality, expect, actual, format) \
    do {\
        test_count++;\
        if (equality)\
            test_pass++;\
        else {\
            fprintf(stderr, "%s:%d: expect: " format " actual: " format "\n", __FILE__, __LINE__, expect, actual);\
            main_ret = 1;\
        }\
    } while(0)

#define EXPECT_EQ_INT(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%d")

在这种情况下EXPECT_EQ_INT(LEPT_PARSE_OK, lept_parse(&v, "null")),if中会先调用一次lept_parse(),如果没得到预期的结果,会在else中将再调用一次lept_parse()

4yannf avatar Oct 08 '21 16:10 4yannf

所以这种宏里面不应该出现函数调用,尽量使用左值

chanchancl avatar Oct 11 '21 02:10 chanchancl

确实是这样

Xiaotian0726 avatar Oct 18 '21 03:10 Xiaotian0726

我也发现了这个问题,有没有什么解释

qunyuanchen avatar Nov 27 '21 11:11 qunyuanchen

这样说我觉得也是。看来得在if中把返回值用变量保存起来,之后再在else中使用。不知道作者怎么解释。

relaxcn avatar Dec 15 '21 07:12 relaxcn