5

If I have multiple if-statements nested inside each other which are all in a for-loop, will a break statement on the inner-most if-statement break out of the for-loop or just into the next if statement?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Sphero
  • 173
  • 1
  • 1
  • 7

3 Answers3

21

It will break the loop (the inner most loop that the if contains in) no matter how many if statments are nested inside. A break breaks from a loop and not from if statement.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Dr.Haimovitz
  • 1,508
  • 10
  • 15
4

break is only for loops and switch statements. It ignores the ifs and it will leave the loop, as required.

SzG
  • 11,777
  • 4
  • 25
  • 38
3

A break statement only has an effect on loops ( do , for , while ) and switch statements (for breaking out of a case ).

if is not a loop in any programming language(not in C++ either). If-else statements are conditional statements where you take some actions if a predefined condition is true or false. There is no loop in if statements. So you can't break if statement since it is not a loop or switch statement.

Hope you understand!

Kishan Lal
  • 193
  • 3
  • 12
  • 1
    What is your source for the claim that `if` is not a loop in any programming language? Did somebody survey every programming language every created, even by a student in a class exercise? Is there no foreign language in which `if` has some other meaning and was used as a loop keyword? Has no assembly language happened to use `if` as a mnemonic for a branch instruction? – Eric Postpischil Aug 15 '18 at 15:01