I've got a question for all of the veteren C++ programmers out there.... I know that in_addr_t is a byte addressed value (representing an IPv4 address) however in debugging this code I was expecting a compile error ( scope of ipaddr declared in if statement would not extend to the else block):

if( in_addr_t ipaddr = inet_addr( s ) == -1 )
      {
         gpstk::Exception ie( "invalid IPv4 inet_addr : " + s );
         GPSTK_THROW(ie);
      }
      else
      {
         inetList.push_back( ipaddr ); 
      }

Instead, what I found is that this code compiles fine but instead pushes zero values onto inetList for every valid IPv4 address ( s == "128.1.1.1" for instance).

If I parenthesize ( in_addr_t ipaddr = inet_addr( s ) ) then I will get the expected compile error and if I declare in_addr_t ipaddr; outside of the if-else statement then everything works as expected... truth be told I understand the fixes a bit more than the problem itself as it seems to me that the declaration and assignment of in_addr_t ipaddr = inet_addr( s ) should either be out of scope (and thus result in a compile error) or should work correctly; however not incorrectly represent the value of ipaddr as zero.

Any thoughts?

Recommended Answers

All 3 Replies

I believe (but since I'm not familiar with IP thingies, I'm not sure) that you are assigning a bool here: in_addr_t ipaddr = inet_addr( s ) == -1 Is the same as in_addr_t ipaddr = (inet_addr( s ) == -1) So you should write: (in_addr_t ipaddr = inet_addr( s )) == -1 but it gives you compile error, so simply try to make in_addr_t outside if statement.

And also, I believe if you declare something inside if (here) it exists in else?

I guess I confused as to why a compile error isn't generated in either circumstance... shouldn't in_addr_t ipaddr be out of scope regardless?

It's not a scope error: ipaddr is in scope from if clause to the end of else clause.
See prev post: you initialize ipaddr by (inet_addr(s) == -1) - it's eaual to false, so ipaddr == 0 after conversion false to in_addr_t.
You should write:

if( in_addr_t ipaddr = inet_addr(s), ipaddr == -1 )
{
    gpstk::Exception ie( "invalid IPv4 inet_addr : " + s );
    GPSTK_THROW(ie);
}
else
{
    inetList.push_back( ipaddr ); 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.