简体   繁体   中英

“Socket operation on non-socket” error due to strange syntax

I ran across the error Socket operation on non-socket in some of my networking code when calling connect and spent a lot of time trying to figure out what was causing it. I finally figured out that the following line of code was causing the problem:

if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol) < 0)) {

See the problem? Here's what the line should look like:

if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {

What I don't understand is why the first, incorrect line doesn't produce a warning. To put it another way, shouldn't the general form:

if ( foo = bar() < baz ) do_something();

look odd to the compiler, especially running with g++ -Wall -Wextra ?

If not, shouldn't it at least show up as "bad style" to cppcheck, which I'm also running as part of my compile?

Actually, you don't get any warning because of the double parenthesis ( .

Try to remove one pair, and you'll get the warning back.

#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;
}

To avoid such annoying mistakes/typos, I avoid assigning a value and testing it in the same statement. That's too much error prone imho.

That's one reason why I try not to do too much in one statement. Instead of

if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {

Why not:

sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)
if(sockfd < 0) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM