在调用connect
时,我在我的一些网络代码中遇到了错误Socket operation on non-socket
,并花费了大量时间试图找出导致它的原因。我最终发现是下面这行代码导致了这个问题:
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol) < 0)) {
看到问题了吗?这条线应该是这样的:
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {
我不明白的是,为什么第一行错误的代码不会产生警告。换句话说,一般的形式不应该是:
if ( foo = bar() < baz ) do_something();
编译器看起来很奇怪,尤其是在g++ -Wall -Wextra
上运行?
如果不是,它至少应该在cppcheck中显示为“糟糕的样式”,我也将其作为编译的一部分运行。
发布于 2010-06-17 17:18:14
实际上,由于使用了双括号(
,您不会收到任何警告。
尝试删除一个对,您将得到警告。
#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;
}
为了避免这种恼人的错误/打字错误,我避免在同一个语句中赋值和测试它。这是太多容易出错的错误了。
发布于 2010-06-17 17:19:11
这就是为什么我尽量不在一条语句中做太多事情的原因之一。而不是
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {
为什么不呢:
sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)
if(sockfd < 0) {
https://stackoverflow.com/questions/3060295
复制相似问题