Cpp - Initialize more than one variable, test a compound logical expression, and execute more than one statement in for loop.

Introduction

When the initialization and action sections contain more than one statement, they are separated by commas. Here's an example:

for (int x = 0, y = 0; x < 10; x++, y++) 
{ 
    std::cout << x * y << "\n"; 
} 

This loop has an initialization section that sets up two integer variables: x and y.

The loop's test section tests whether x < 10.

The loop's action section increments both integer variables, using a comma between the statements.

The body of the loop displays the product of multiplying the variables together.

Each section of a for loop can be empty.

The semicolons are still there to separate sections, but some of them contain no code. Here's an example:

int x = 0; 
int y = 0; 
for ( ; x < 10; x++, y++) 
{ 
    std::cout << x * y << "\n"; 
} 

Related Topic