Socket error on offline error due to strange syntax

I encountered a Socket operation on non-socket error in some of my network code when I called connect and spent a lot of time trying to figure out what was causing it. Finally, I realized that the following line of code is causing the problem:

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

See the problem? This is what the line looks like:

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

I do not understand why the first incorrect line does not cause a warning. In other words, there should not be a general view:

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

Looks weird for the compiler, especially works with g++ -Wall -Wextra ?

If not, should it at least show up as a "bad style" for cppcheck, which I also run as part of my compilation?

+4
source share
2 answers

In fact, you are not getting warnings due to double brackets ( .

Try removing one pair and you will get a warning.

 #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 errors / typos, I avoid assigning a value and testing it in the same statement. This is too much error prone to IMHO.

+5
source

This is one of the reasons why I try not to do too much in one statement. Instead

 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) { 
+2
source

Source: https://habr.com/ru/post/1313066/


All Articles