Is there ever a need for a “do {…} while ( )” loop?

后端 未结 19 2286
清歌不尽
清歌不尽 2020-11-29 02:44

Bjarne Stroustrup (C++ creator) once said that he avoids \"do/while\" loops, and prefers to write the code in terms of a \"while\" loop instead. [See quote below.]

S

19条回答
  •  Happy的楠姐
    2020-11-29 03:21

    do { ... } while (0) is an important construct for making macros behave well.

    Even if it's unimportant in real code (with which I don't necessarily agree), it's important for for fixing some of the deficiencies of the preprocessor.

    Edit: I ran into a situation where do/while was much cleaner today in my own code. I was making a cross-platform abstraction of the paired LL/SC instructions. These need to be used in a loop, like so:

    do
    {
      oldvalue = LL (address);
      newvalue = oldvalue + 1;
    } while (!SC (address, newvalue, oldvalue));
    

    (Experts might realize that oldvalue is unused in an SC Implementation, but it's included so that this abstraction can be emulated with CAS.)

    LL and SC are an excellent example of a situation where do/while is significantly cleaner than the equivalent while form:

    oldvalue = LL (address);
    newvalue = oldvalue + 1;
    while (!SC (address, newvalue, oldvalue))
    {
      oldvalue = LL (address);
      newvalue = oldvalue + 1;
    }
    

    For this reason I'm extremely disappointed in the fact that Google Go has opted to remove the do-while construct.

提交回复
热议问题