Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CPlusPlusNotesForProfessionals.pdf
Скачиваний:
47
Добавлен:
20.05.2023
Размер:
5.11 Mб
Скачать

The initialization and increment statements can perform operations unrelated to the condition statement, or nothing at all - if you wish to do so. But for readability reasons, it is best practice to only perform operations directly relevant to the loop.

A variable declared in the initialization statement is visible only inside the scope of the for loop and is released upon termination of the loop.

Don't forget that the variable which was declared in the initialization statement can be modified during the loop, as well as the variable checked in the condition.

Example of a loop which counts from 0 to 10:

for (int counter = 0; counter <= 10; ++counter)

{

std::cout << counter << '\n';

}

// counter is not accessible here (had value 11 at the end)

Explanation of the code fragments:

int counter = 0 initializes the variable counter to 0. (This variable can only be used inside of the for loop.)

counter <= 10 is a Boolean condition that checks whether counter is less than or equal to 10. If it is true, the loop executes. If it is false, the loop ends.

++counter is an increment operation that increments the value of counter by 1 ahead of the next condition check.

By leaving all statements empty, you can create an infinite loop:

// infinite loop for (;;)

std::cout << "Never ending!\n";

The while loop equivalent of the above is:

// infinite loop while (true)

std::cout << "Never ending!\n";

However, an infinite loop can still be left by using the statements break, goto, or return or by throwing an exception.

The next common example of iterating over all elements from an STL collection (e.g., a vector) without using the

<algorithm> header is:

std::vector<std::string> names = {"Albert Einstein", "Stephen Hawking", "Michael Ellis"}; for(std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) {

std::cout << *it << std::endl;

}

Section 11.3: While loop

A while loop executes statements repeatedly until the given condition evaluates to false. This control statement is used when it is not known, in advance, how many times a block of code is to be executed.

For example, to print all the numbers from 0 up to 9, the following code can be used:

int i = 0;

GoalKicker.com – C++ Notes for Professionals

48

while (i < 10)

{

std::cout << i << " "; ++i; // Increment counter

}

std::cout << std::endl; // End of line; "0 1 2 3 4 5 6 7 8 9" is printed to the console

Version ≥ C++17

Note that since C++17, the first 2 statements can be combined

while (int i = 0; i < 10) //... The rest is the same

To create an infinite loop, the following construct can be used:

while (true)

{

// Do something forever (however, you can exit the loop by calling 'break'

}

There is another variant of while loops, namely the do...while construct. See the do-while loop example for more information.

Section 11.4: Do-while loop

A do-while loop is very similar to a while loop, except that the condition is checked at the end of each cycle, not at the start. The loop is therefore guaranteed to execute at least once.

The following code will print 0, as the condition will evaluate to false at the end of the first iteration:

int i =0; do

{

std::cout << i;

++i; // Increment counter

}

while (i < 0);

std::cout << std::endl; // End of line; 0 is printed to the console

Note: Do not forget the semicolon at the end of while(condition);, which is needed in the do-while construct.

In contrast to the do-while loop, the following will not print anything, because the condition evaluates to false at the beginning of the first iteration:

int i =0; while (i < 0)

{

std::cout << i;

++i; // Increment counter

}

std::cout << std::endl; // End of line; nothing is printed to the console

Note: A while loop can be exited without the condition becoming false by using a break, goto, or return statement.

int i = 0; do

{

GoalKicker.com – C++ Notes for Professionals

49

std::cout << i;

++i; // Increment counter if (i > 5)

{

break;

}

}

while (true);

std::cout << std::endl; // End of line; 0 1 2 3 4 5 is printed to the console

A trivial do-while loop is also occasionally used to write macros that require their own scope (in which case the trailing semicolon is omitted from the macro definition and required to be provided by the user):

#define BAD_MACRO(x) f1(x); f2(x); f3(x);

// Only the call to f1 is protected by the condition here if (cond) BAD_MACRO(var);

#define GOOD_MACRO(x) do { f1(x); f2(x); f3(x); } while(0)

// All calls are protected here if (cond) GOOD_MACRO(var);

Section 11.5: Loop Control statements : Break and Continue

Loop control statements are used to change the flow of execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. The break and continue are loop control statements.

The break statement terminates a loop without any further consideration.

for (int i = 0; i < 10; i++)

{

if (i == 4)

break; // this will immediately exit our loop std::cout << i << '\n';

}

The above code will print out:

1

2

3

The continue statement does not immediately exit the loop, but rather skips the rest of the loop body and goes to the top of the loop (including checking the condition).

for (int i = 0; i < 6; i++)

{

if (i % 2 == 0) // evaluates to true if i is even

continue; // this will immediately go back to the start of the loop

/* the next line will only be reached if the above "continue" statement does not execute */

std::cout << i << " is an odd number\n";

}

The above code will print out:

GoalKicker.com – C++ Notes for Professionals

50

1 is an odd number

3 is an odd number

5 is an odd number

Because such control flow changes are sometimes di cult for humans to easily understand, break and continue are used sparingly. More straightforward implementation are usually easier to read and understand. For example, the first for loop with the break above might be rewritten as:

for (int i = 0; i < 4; i++)

{

std::cout << i << '\n';

}

The second example with continue might be rewritten as:

for (int i = 0; i < 6; i++)

{

if (i % 2 != 0) {

std::cout << i << " is an odd number\n";

}

}

Section 11.6: Declaration of variables in conditions

In the condition of the for and while loops, it's also permitted to declare an object. This object will be considered to be in scope until the end of the loop, and will persist through each iteration of the loop:

for (int i = 0; i < 5; ++i) { do_something(i);

}

// i is no longer in scope.

for (auto& a : some_container) { a.do_something();

}

// a is no longer in scope.

while(std::shared_ptr<Object> p = get_object()) { p->do_something();

}

// p is no longer in scope.

However, it is not permitted to do the same with a do...while loop; instead, declare the variable before the loop, and (optionally) enclose both the variable and the loop within a local scope if you want the variable to go out of scope after the loop ends:

//This doesn't compile do {

s = do_something(); } while (short s > 0);

// Good short s; do {

s = do_something(); } while (s > 0);

GoalKicker.com – C++ Notes for Professionals

51