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

tutorial01中 leptjson.c 中 EXPECT(c,ch) 的问题

Open limingwong opened this issue 7 years ago • 3 comments

在函数:

static int lept_parse_value(lept_context* c, lept_value* v) {
    switch (*c->json) {
            case 'n':  return lept_parse_null(c, v);
            case 't':  return lept_parse_true(c,v);
            case 'f':  return lept_parse_false(c,v);
            case '\0': return LEPT_PARSE_EXPECT_VALUE;
            default:   return LEPT_PARSE_INVALID_VALUE;
    }
}

中已经对json的第一个字母进行了判断,为什么在解析函数中还要调用宏 EXPECT(c,ch)再判断一下第一个字母是不是符合要求,是否必要?

解析函数如下:

static int lept_parse_null(lept_context* c, lept_value* v) {
    EXPECT(c, 'n');
    if (c->json[0] != 'u' || c->json[1] != 'l' || c->json[2] != 'l')
        return LEPT_PARSE_INVALID_VALUE;
    c->json += 3;
    if (!lept_isblank(c))
        return LEPT_PARSE_ROOT_NOT_SINGULAR;
    v->type = LEPT_NULL;
    return LEPT_PARSE_OK;
}

limingwong avatar Jun 13 '18 09:06 limingwong

#define EXPECT(c, ch)       do { assert(*c->json == (ch)); c->json++; } while(0)

也只是在调试模式下做 assert(),一种防御性的编程方法,不是必要。但 c->json++ 是必要的。

miloyip avatar Jun 13 '18 09:06 miloyip

好的,谢谢!

limingwong avatar Jun 13 '18 10:06 limingwong

感觉这样理解,比较舒服: ”作为功能函数封装,还是需要考虑这个函数单独调用时候的场景“。 lept_parse_null()是作为一个功能函数进行封装,只是正好在lept_parse_value()函数中被调用。 如果在其他的函数中被调用,可能其他的函数中并没有像 lept_parse_value()函数中那样对 *c->json 进行了检查。 所以在lept_parse_null()函数自身中,一定要是需要进行一些自己的检查的。

当然,这个项目中只是简单调用一下这个函数,但想着,如果是实际工程项目,还是应该像作者这样书写。

cshuazhang avatar Jul 15 '18 12:07 cshuazhang