请问 C++里单独一行的(void)ch; 什么意思?( json11 里的一段代码)

2015-10-08 16:50:58 +08:00
 iambic

在看 dropbox 的 json11 源码,json11 是 dropbox 公司开源的 C++解析 json 的库。

地址在 https://github.com/dropbox/json11
其中有一处的写法很奇怪(json11.cpp, line632 - line651)
https://github.com/dropbox/json11/blob/master/json11.cpp#L651

while (1) {           
    i--;                                                                                          
    data.push_back(parse_json(depth + 1));                            
    if (failed)                                                                                   
        return Json();                                                                            

    ch = get_next_token();                                                                        
    if (ch == ']')                                                                                
        break;                                                                                    
    if (ch != ',')                                                                                
        return fail("expected ',' in list, got " + esc(ch));                                      

    ch = get_next_token();                                                                        
    (void)ch;   
}

这里的 get_next_token 返的的是一个 char 类型,即 ch 就是一个普通的 char 类型
我的问题是,最后一行,单独的一行( https://github.com/dropbox/json11/blob/master/json11.cpp#L651

(void)ch;

是什么意思?感觉没有任何作用啊?

谢谢!

2886 次点击
所在节点    问与答
8 条回复
timonwong
2015-10-08 16:55:44 +08:00
没有任何作用,这个是绕过 compiler/linter 警告的( unused variable )
当然,对部分编译器,使用这行代码也无意义,仍然要给你报 unused variable 警告
acros
2015-10-08 16:58:43 +08:00
参考楼上说的歪头想了一下。
clang 对于未使用变量是不是挺敏感来着··· 很多我在 vs 下出 warning 的,它都直接扔 error
wshcdr
2015-10-08 16:59:01 +08:00
没什么作用的
iambic
2015-10-08 16:59:20 +08:00
@timonwong 明白了,多谢!
legendlee
2015-10-08 18:12:14 +08:00
如果不加,编译器会抛出警告。
Cloudee
2015-10-08 20:49:10 +08:00
ch = get_next_token();
(void)ch;

里面这个 ch 确实什么情况都用不到了,为啥不直接

get_next_token();

bengol
2015-10-08 21:01:53 +08:00
@Cloudee 挂 debuger 的时候能看到返回值
Cloudee
2015-10-09 13:31:44 +08:00
@bengol 我去,没想到还有这种用法,受教了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/226360

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX