“break;” out of “if” statement?

后端 未结 4 810
有刺的猬
有刺的猬 2020-12-09 07:41

Can you break out of an if statement or is it going to cause crashes? I\'m starting to acquaint myself with C, but this seems controversial. The first image is from a book o

4条回答
  •  悲哀的现实
    2020-12-09 08:15

    As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing https://stackoverflow.com/a/257421/1188057 as nobody else mentioned it. It's just a trick involving the do-while loop.

    do {
      // do something
      if (error) {
        break;
      }
      // do something else
      if (error) {
        break;
      }
      // etc..
    } while (0);
    

    Though I would prefer the use of goto-statement.

提交回复
热议问题