Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost::asio what is this kind of strange coding style?

I am about to debug something within my boost asio socket communication. And found this piece of code inside of the asio library (found in boost/asio/impl/write.hpp line 169 (boost 1.47) ):

  switch (start)
  {
    case 1:
    buffers_.prepare(this->check_for_completion(ec, total_transferred_));
    for (;;)
    {
      stream_.async_write_some(buffers_,
          BOOST_ASIO_MOVE_CAST(write_op)(*this));
      return; 
    default:
      total_transferred_ += bytes_transferred;
      buffers_.consume(bytes_transferred);
      buffers_.prepare(this->check_for_completion(ec, total_transferred_));
      if ((!ec && bytes_transferred == 0)
          || buffers_.begin() == buffers_.end())
        break;
    }

    handler_(ec, static_cast<const std::size_t&>(total_transferred_));
  }

I have already a lot of years of C/C++ development experience, but never ever in my life I saw such kind of weird implementation. Look there, the default: label of the switch statement is within the for loop.

If I understand this right, then the switch statement is "misused" instead of a goto, right (for the cases where start != 1, goto default:)? Is it actually a valid C/C++ with respect to the standard? What will happen if I for example put

for(int i=0; i < 10; i++)

instead of the for loop in the original code. Will "i" be undefined in case when jump is performed to default: label? Sure I might use a debugger here, however this seems so suspicious for me, that I think this could produce different behavior for different compilers.

like image 592
cgart Avatar asked Nov 09 '11 11:11

cgart


People also ask

What is Boost ASIO?

Boost. Asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach. Overview. An overview of the features included in Boost. Asio, plus rationale and design information.

Does boost ASIO use threads?

At its core, Boost Asio provides a task execution framework that you can use to perform operations of any kind. You create your tasks as function objects and post them to a task queue maintained by Boost Asio. You enlist one or more threads to pick these tasks (function objects) and invoke them.

Is boost ASIO header only?

By default, Boost. Asio is a header-only library. However, some developers may prefer to build Boost. Asio using separately compiled source code.


1 Answers

This is well-defined, valid code. A switch really is a glorified goto. For some clever use of this construct, take a look at Duff's device.

As for your for, that wouldn't be legal. A jump to a case label can't cross an initialization.

like image 170
David Schwartz Avatar answered Sep 18 '22 23:09

David Schwartz