Rob*_*nes 4 c c++ g++ cppcheck
我Socket operation on non-socket在调用时遇到了一些网络代码中的错误,connect并花了很多时间试图找出导致它的原因.我终于发现以下代码行导致了问题:
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol) < 0)) {
Run Code Online (Sandbox Code Playgroud)
看到问题?这是该行应该是什么样子:
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {
Run Code Online (Sandbox Code Playgroud)
我不明白的是为什么第一行不正确的行不会产生警告.换句话说,不应该是一般形式:
if ( foo = bar() < baz ) do_something();
Run Code Online (Sandbox Code Playgroud)
看起来奇怪的编译器,尤其是运行g++ -Wall -Wextra?
如果不是,它不应该至少表现为cppcheck的"坏样式",我也在编译中运行吗?
实际上,由于双括号,您不会收到任何警告(.
尝试删除一对,然后您将收到警告.
#include <iostream>
int foo()
{
return 2;
}
int main(int /*argc*/, char** /*argv*/)
{
int l;
if ((l = foo() < 3)) // Won't generate warning under gcc
{
}
if (l = foo() < 3) // will generate a warning "warning: suggest parentheses around assignment used as truth value"
{
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
为了避免这种恼人的错误/错别字,我避免分配值并在同一语句中测试它.这太容易出错了imho.