2

質問が 1 つあります。助けてください。Web ページで do while ステートメントについて読んだことがあります。異なるのは、while にはブール条件ではなく 0 が書かれているということです。

do{
   // do some instruction
}while(condition );

はっきりと理解できますが、これは

 do
  {
    //again some instruction
  }while(0);

私はそれが何をするのか推測できませんか?それはこれと同等ですか: while(false) を実行しますか?それとも無限ループですか?助けてください

4

5 に答える 5

6

それは一度だけ何かをします。ステートメントをグループ化し、使用法をより自然にするためにマクロで広く使用されています(つまり、セミコロンで終了する必要があります)。

そのソルトに値するコンパイラは、 do .. while を完全に無視し、囲まれたステートメントを実行するだけです。

于 2011-10-18T05:54:52.620 に答える
3

この「ループ」は一度だけ実行されますが、次のように使用できます。

do
{
  // declare some local variables only visible here
  // do something

  if(TestSomeConditions())
      break;

  // do something more
  // destructors of local variables run here automatically
}while(0);

私見、ほとんどの場合、これをより構造化された方法で書き直す方が良いです。

  // do something
  if(!TestSomeConditions())
  {
      // do something more
  }

または、元のスコープを反映して別の関数を導入することによって:

  void MyFunction()
  {
      // declare some local variables only visible here
      // do something

      if(TestSomeConditions())
          return;

      // do something more
  }
于 2011-10-18T05:58:41.287 に答える
1

The do while loop executes all the instructions in the body of the loop first and then checks for the condition. Hence, this loop just executes the instructions of the body of the loop once.

do
{
    //my instructions
}while(0)

is equivalent to writing

{
    //my instructions
}

The modern compilers are smart enough to optimize these things out!

于 2011-10-18T05:57:57.047 に答える
1

0 を false として扱い、1 回のループが実行され、while に達するとすぐに中断します (g++ コンパイラでテスト済み)。

于 2011-10-18T06:00:12.250 に答える
1

技術的に言えば、一度実行した後にチェックする(そしてチェックに失敗する)ため、一度実行します。

それ以外は、マクロで使用されます。例えば:

#define blah(a) \
        something(1); \
        something(2)

if(a)
    blah(4);
else
    blah(19);

これにつながります:

...
if(a)
    something(1); something(2);
else
    something(1); something(2);

else は if ステートメントの一部ではないため、これは有効な構文ではありません。あなたができることは次のとおりです。

 define blah(a) \
    do {
       something(1); something(2);
    } while(0)

    ...

これは、if ブロック内の単一のステートメントに変換されます。

if(a)
    do { something(1); something(2); } while(0);
else
    ...
于 2011-10-18T06:07:46.820 に答える