Ice s. Woo
Ice s. Woo

Reputation: 27

Is it break my for loop in c++?

for(size_t i=0;i<vec.size();i++){
    if(n>vec[i]){
        a=i;
        break;
    }
}

in this example, am I breaking the if statement or the for loop?

Upvotes: 1

Views: 115

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158459

The break statement is used to break out of a switch or iteration statement i.e. a while, do or for loop. The C++ draft standard section 6.6.1 The break statement says:

The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.

Since the if is not an iteration statement or a switch then the break will leave the for loop.

Upvotes: 4

Bill the Lizard
Bill the Lizard

Reputation: 405715

A break statement ends only the do, for, switch, or while statement that immediately encloses it. It doesn't break out of an if statement, so your code is breaking out of the loop.

Upvotes: 1

Paddyd
Paddyd

Reputation: 1870

It will break from the for loop.

In loops, the break statement ends execution of the nearest enclosing do, for, or while statement.

Source: Microsoft docs

Upvotes: 0

Related Questions