8

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
  • 115,751
  • 26
  • 228
  • 437
Sphero
  • 303
  • 1
  • 3
  • 8

3 Answers3

27

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
  • 730,956
  • 141
  • 904
  • 1,278
Dr.Haimovitz
  • 1,568
  • 12
  • 16
4

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

SzG
  • 12,333
  • 4
  • 28
  • 41
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
  • 473
  • 1
  • 5
  • 13
  • 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