Avoid for loop with 0

Ingo Förster
Ingo Förster used Ask the Experts™
on
I have a beginner question about c++. How I can avoid that the for loops run when FirstSession and LastSession both are 0.

   
 for (int32 i = mi.nFirstSession; i <= mi.nLastSession; i++)
{

Open in new window


Currently it will run if FirstSession and LastSession are 0.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
if (mi.nFirstSession == 0 || mi.nLastSession == 0)
{
for (int32 i = mi.nFirstSession; i <= mi.nLastSession; i++)
{}
}

Open in new window

Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
Above should be
if (mi.nFirstSession != 0 || mi.nLastSession != 0)
  for (int32 i = mi.nFirstSession; i <= mi.nLastSession; i++)
  {}

Open in new window

"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
Or you include that condition into the for check - which I do not recommend, as you should only put there something which can change while the loop is running.
for (int32 i = mi.nFirstSession; i <= mi.nLastSession && (mi.nFirstSession != 0 || mi.nLastSession != 0); i++)
{}

Open in new window

Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

@David,
Could you take a look at your if statement again. If both terms are 0, then the for  loop is still performed.
Top Expert 2016

Commented:
it was supposed to be NOT equal rather than Equal. Qlemo fixed it.

Author

Commented:
Many thanks for the solution. Special to Qlemo.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial