In design phase. Is this layout/syntax correct?

Pages: 12
My question is about the code posted below. As stated in the title, I'm in the design phase for this part of a program. I have never used "continue;" before. And the info that I researched wasn't very descriptive for how I may be using it. Here is a description for what I'm trying to accomplish.

Each FOR loop iterates over something(each for loop is different) then it compares something(the IF statement), when the IF statement is TRUE, it hits the "continue;" then goes back "up" to the FOR loop for another iteration and then checks "IF" statement again. Then when the FOR loop has finished all iterations and passed IF statement, it jumps "down" to the next FOR loop, and processes, just like explained for the previous FOR loop. Now, ALL 3 FOR loops must process and pass the IF statement criteria, in order for the COUT statement to execute. If at any point in the nested loops, the code does not pass the conditions. It breaks out of the code and increases (++a) and jumps up to the WHILE loop and starts FOR looping again. I do have comments in the code to help describe.

I thought of using an if/elseif ladder, but each FOR loop iterates over different things or has different starting points.

So, in short, what I'm trying to accomplish: Each FOR loop must pass in order for the COUT to execute. If at any point, an IF statement becomes FALSE, it breaks out of every loop, then "++a" and starts from the while loop again. I haven't tried coding this yet, as for I'm trying to design this part first, and never did anything like this before. Is the layout/syntax correct?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    while (a < t5.size){
        for (  ) {   // used to loop thru something for 'i' times, and increment also included
            if  (   )   // used for comparison  ex.   a !< b
                continue;   // when if statement is true.  Does this make it hop UP (2 lines) to the for loop??
                    for (  ){  // used to loop thru something for 'j' times, and increment also included
                        if (   )   // used for comparison  ex.   a != c
                            continue;   // when if statement is true.  Does this make it hop UP (2 lines) to the for loop??
                                for (  ){  // used to loop thru something for 'k' times, and increment also included
                                    if  (  )   // used for comparison  ex.   a != d
                                        continue;   // when if statement is true.  Does this make it hop UP (2 lines) to the for loop??
                                    break;
                                }
                        break;
                    }
            break;
        }
        
        std::cout << "Line No. " << a << " has passed criteria" << std::endl;
        ++a;
    }

EDIT: Looks like it's hitting the std::cout each time. It should probably be indented under the last "continue"??
Last edited on
indentation does not affect c++, its for the humans.

yes, continue hops 2 lines to the for loop if the condition is true. It forces the current scope loop to stop its current iteration and move to the next iteration. consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

int main()
{
  for(int i = 1; i < 4; i++)
  {
	 cout << "i loop:\n";
	 for(int j = 0; j < 10; j++)
	 {
       if(j%2)
       continue;
       cout << j << endl;	   
		 
	 }	 	  
  }  	
}

outputs:
i loop:
0
2
4
6
8
i loop:
0
2
4
6
8
i loop:
0
2
4
6
8


but the breaks are unclear in purpose. Break causes the current loop to stop all iterations, but why / what you are trying to do with them here I don't know.

this looks like a confusing to read, overcooked design. Overuse of breaks and continues is hard to follow, and while I know its an example, take a deeper look at the problem to see if there is a better way.
It sure looks like there would be a way to do this, perhaps:

1
2
3
4
5
6
7
while(...)
{
      if(a < something && a != other && a > third)
          cout //here, a passed
     //modify the 3 condition variables in some way
     //modify a     
}


the trick is whether the breaks and continues save a lot of processing. If they do, your approach may be the best one regardless.
Last edited on
The while loop is for checking each row of a 2d vector against certain situations(the for loops with if statements) to qualify. Since SPEED is of the essence here, the for loops that are the fastest are at the top of the code(qualifing) process. I don't want to execute all the for loops if one of the IF statements returns FALSE. If the statement returns false, Exit all for loops and ++a in the while loop(for next row in 2d vector) and start for looping again. There could possibly be 10 or more different FOR loops the row(in the while loop) must pass. ONLY when it passes ALL the FOR loops, will the COUT get excecuted. For speed purposes, the fastest for loops are at the beginning of the code.

Just wasn't sure about the indentation and placement of curly braces plus where to put the std::cout statement. I thought it was necessary to indent each For loop one step more than the previous one. I don't want to continue FOR looping if I get a FALSE for an IF statement. I only want to cout if all 10 FOR loops(if statements) PASS (=TRUE).
Last edited on
indents are nice, that is the proper thing to do for reading it, but has no effect on the compiler.

if its speed critical, the break/continue model may be the best way. You may want to check the specific problem stuff in great detail though, to see if some of the loops can be combined or anything else tweaked. It is easy to miss redundant iteration or logic for things that are related that you didn't expect. It may also be better to split the checks into threads instead of sequential for loops, do all of them at once? Won't work if the inner depends on the outer, but that is unclear if the dependency is real or constructed for your needs.
Last edited on
It sounds like the behavior you want would better be achieved by std::none/all/any_of with a suitable parallel execution policy. Of course you didn't tell us about your actual problem so I can't produce concrete examples.
https://xyproblem.info/

You really shouldn't be attempting to micro-optimize a program you haven't written yet. You can choose to code a better algorithm, but that's more or less all that can be done reliably without measuring.

Consider, e.g:
1
2
3
4
5
6
7
8
9
10
auto const geq_0    = [](auto const x) { return x >= 0; };
auto const lt_900mm = [](auto const x) { return x < 900'000'000; };

for (int row = 0; row < 1; ++row)
{
  // e.g.: skip this row if not all elements in the vector are >= 0
  if (! std::all_of(std::execution::par_unseq, begin, end, geq_0)) continue;
  if (! std::all_of(std::execution::par_unseq, begin, end, lt_900mm)) continue;
  // ...
}
Last edited on
jonnin:
indentation does not affect c++, its for the humans.
indents are nice, that is the proper thing to do for reading it, but has no effect on the compiler.
I did NOT know this. Thanks!

the break/continue model may be the best way.
If this is correct, is the following layout/syntax correct??? I know it's probably not the most optimized way of doing this, but, for now, since I'm in the early learning stages, will this layout perform the way I want????

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    int a {0};
    while (a < t5.size){   // used to cycle each row in a 2d vector.
        for (  ) {   // Ex: used to iterate through a vector 16 times with ++ after each iteration
            if  (   )   // used for comparison  after iteration Ex.   a != b
            continue;   // 
                    for (  ){  // Ex: used to iterate through a different vector 48 times with ++ after each iteration
                        if (   )   // used for comparison  Ex.   a != c
                        continue;   // 
                                for (  ){  // Ex: used to iterate through a 2dvector 12 times with ++ after each iteration
                                    if  (  )   // used for comparison after iteration Ex.   a != d
                                    continue;   // 
                                        for (  ){  // Ex: used to iterate through a different 2dvector 460 times with ++ after each iteration
                                            if  (  )   // used for comparison after iteration Ex.   a != e
                                            continue;   // 
                                                for (  ){  // Ex: used to iterate through a 2dvector 1142 times with ++ after each iteration
                                                    if  (  )   // used for comparison  after iteration Ex.   a != f
                                                    continue;   // 
                                                        std::cout << "Line No. " << row << " has passed ALL criteria" << std::endl;
                                                    break;
                                                }
                                            break;
                                        }
                                    break;
                                }
                        break;
                    }
            break;
        }
        ++a;
    }


mbozzi:
Thanks for your reply! I'm not that advanced yet to understand what your example is telling me. Sorry about that! I'm very new and self taught. Don't think the xyproblem.info was accurate though. I'm just not as advanced as you are! BUT, I'm trying to learn!!!
Last edited on
It seems I'm not getting the correct output with the layout above, UGH!!!

Anyone have any ideas for another way?? I would like to use FOR loops if possible. It may not be the fastest/optimized way. But for a newbie like myself, I need to understand what it's doing.
Don't think the xyproblem.info was accurate though

Good luck getting help.
I thought I was very clear in my explanations. I mean no disrespect. I do really need help. I tried different things using the debugger in my ide. It hits the continue just fine. But when the if statement becomes false, it jumps to the next for loop, instead of breaking the full cycle and jumping up to the while loop. Again, sorry but no disrespect.
continue executes the current loop again. Break jumps out of the current loop. So this:
1
2
3
4
5
6
    for () {
        statements;
        if (cont) continue;
        more_statements;
        if (cond2) break;
    }

is exactly(?) the same as this:
1
2
3
4
5
6
7
8
    for () {
        statements;
        if (cond) goto 1;
        more_statements;
        if (cond2) goto 2;
    1:
    }
 2:


If the statement returns false, Exit all for loops and ++a in the while loop
Unfortunately, you can't break out of more than one loop at a time. Since you have several, I suggest that you put the for loops in a function and return from the function instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    int a {0};
    while (a < t5.size){   // used to cycle each row in a 2d vector.
        func();
    }

void func()
{
        for (  ) {   // Ex: used to iterate through a vector 16 times with ++ after each iteration
            if  (   )   // used for comparison  after iteration Ex.   a != b
            return;   // 
                    for (  ){  // Ex: used to iterate through a different vector 48 times with ++ after each iteration
                        if (   )   // used for comparison  Ex.   a != c
                        return;   // 
                                for (  ){  // Ex: used to iterate through a 2dvector 12 times with ++ after each iteration
                                    if  (  )   // used for comparison after iteration Ex.   a != d
                                    return;   // 
                                        for (  ){  // Ex: used to iterate through a different 2dvector 460 times with ++ after each iteration
                                            if  (  )   // used for comparison after iteration Ex.   a != e
                                            return;   // 
                                                for (  ){  // Ex: used to iterate through a 2dvector 1142 times with ++ after each iteration
                                                    if  (  )   // used for comparison  after iteration Ex.   a != f
                                                    return;   // 
                                                        std::cout << "Line No. " << row << " has passed ALL criteria" << std::endl;
                                                    break;
                                                }
                                            break;
                                        }
                                    break;
                                }
                        break;
                    }
            break;
        }
        ++a;
    }


But I question how your original loops work. The way you've indented your code doesn't match the block structure. This is more accurate:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void
f()
{
    while (a < t5.size) {
	for () {				 // used to loop thru something for 'i' times, and increment also included
	    if ()				 // used for comparison  ex.   a !< b
		continue;			 // when if statement is true.  Does this make it hop UP (2 lines) to the for loop??
	    for () {				 // used to loop thru something for 'j' times, and increment also included
		if ()				 // used for comparison  ex.   a != c
		    continue;			 // when if statement is true.  Does this make it hop UP (2 lines) to the for loop??
		for () {			 // used to loop thru something for 'k' times, and increment also included
		    if ()			 // used for comparison  ex.   a != d
			continue;		 // when if statement is true.  Does this make it hop UP (2 lines) to the for loop??
		    break;
		}
		break;
	    }
	    break;
	}

	std::cout << "Line No. " << a << " has passed criteria" << std::endl;
	++a;
    }
}


and that's the same as :
1
2
3
4
5
6
7
8
9
10
11
12
13
    while (a < t5.size) {
        for () {                        // used to loop thru something for 'i' times, and increment also included
            if (!cond)                  // used for comparison  ex.   a !< b
                for () {                // used to loop thru something for 'j' times, and increment also included
                    if (!cond)          // used for comparison  ex.   a != c
                        for () {        // used to loop thru something for 'k' times, and increment also included
                            if (!cond)  // used for comparison  ex.   a != d
                                break;
                        }
                    break;
                }
            break;
        }


But now what are all these breaks doing?

So my big question to you is why are these for loops here? What are they actually iterating over? Once you find the right condition, do you stop the current loop?

Do you really mean something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void f()
{
    while (a < t5.size) {
	func();
	++a;
    }
}

void f()
{
    // Search for first condition
    for (x=0; x<i; ++x) {	  // loop thru something for 'i' times
	if (!cond) break;
    }
    if (x == i) return;	  // Never found the condition

    // search for 2nd condition
    for (x=0; x<j; ++x) {	  // loop thru something for 'i' times
	if (!cond) break;
    }
    if (x == j) return;	  // Never found the condition
    // etc.

    // If you get here then all conditions were met
    std::cout << "Line No. " << a << " has passed criteria" << std::endl;
}

I thought I was very clear in my explanations.

Your explanation is fine but it lacks context. Despite your disagreement, such context has shown to be helpful in solving many past problems.

I asked for context and you refused. I'm not offended, but I won't contribute further.
Last edited on
I thought I was very clear in my explanations.

Unfortunately, I think not. Consider this:
I don't want to execute all the for loops if one of the IF statements returns FALSE. If the statement returns false, Exit all for loops and ++a in the while loop(for next row in 2d vector) and start for looping again.
Given this statement, the only way to print the output is when the if statements are true on the first iteration of their corresponding for loop. Put another way, if the if statement is false on the first iteration of any loop, then you say you need to return to the while loop and start again.

So if your explanation is correct then you don't need for loops at all. if statements will do.

I think mbozzi's correct that this is an xyproblem. You are are describing your algorithm but you haven't described the problem that you're trying to solve.
My ignorance in C++ is really showing!! Trying to learn on my own is not an easy task. Just when you think you understand something, you try to use it in your code, and things don't workout! Yes indeed, it does get frustrating at times. The only education I'm getting in c++ is a course on Udemy and I also have 2 books. I have found that the biggest drawback from being self taught, is that there is nobody to talk to, or ask questions. Just have to re-watch the video, or re-read what you don't understand. Sometimes it doesn't cover very detailed aspect of the topic, or how you want to apply it. That was the case with this initial post. I will explain what I mean in a moment. But first!

To mbozzi, My apologies to you. I didn't think the actual context was that important. I NOW realize that what I'm trying to do can't be done the way I thought. I thought I understood the for loop structure and rules of scope. I thought it was a simple question, but one that I never crossed before. I didn't think that the actual details inside the FOR loops and If statements were pertinent info. I thought that just my explanation would be sufficient. Once again, my ignorance/level of experience really shined!! I took your xyproblem link the wrong way. I totally understand "that you won't contribute further". But, I'm in the early stages of learning and I know that I will have other threads with questions, and I hope we can work together on another topic in the future.

My understanding of FOR loops nested within other FOR loops and the use of scope, was not what I thought it was. In this example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    int a {0};
    while (a < t5.size){   // used to cycle each row in a 2d vector.
        for (  ) {   // Ex: used to iterate through a vector 16 times with ++ after each iteration
            if  (   )   // used for comparison  after iteration Ex.   a != b
            continue;   // 
                    for (  ){  // Ex: used to iterate through a different vector 48 times with ++ after each iteration
                        if (   )   // used for comparison  Ex.   a != c
                        continue;   // 
                                for (  ){  // Ex: used to iterate through a 2dvector 12 times with ++ after each iteration
                                    if  (  )   // used for comparison after iteration Ex.   a != d
                                    continue;   // 
                                        for (  ){  // Ex: used to iterate through a different 2dvector 460 times with ++ after each iteration
                                            if  (  )   // used for comparison after iteration Ex.   a != e
                                            continue;   // 
                                                for (  ){  // Ex: used to iterate through a 2dvector 1142 times with ++ after each iteration
                                                    if  (  )   // used for comparison  after iteration Ex.   a != f
                                                    continue;   // 
                                                        std::cout << "Line No. " << row << " has passed ALL criteria" << std::endl;
                                                    break;
                                                }
                                            break;
                                        }
                                    break;
                                }
                        break;
                    }
            break;
        }
        ++a;
    }

I thought when one of the IF statements becomes false, that it would hit the corresponding BREAKS(according to indentation) and keep breaking and breaking until it would hit the ++a and start at the first FOR loop again. I was under the impression that once one of the FOR loops/IF statements would fail, that it wouldn't execute the further NESTED FOR loops. That's is what all the breaks were for. I just thought it would(when IF condition became false) keep breaking until it hit the ++a at the bottom and start all over again. WOW!!! was I wrong!

A better explanation with explicit details to follow. I'll be right back.

I thought I was very clear in my explanations.

Unfortunately, I think not. Consider this:
I don't want to execute all the for loops if one of the IF statements returns FALSE. If the statement returns false, Exit all for loops and ++a in the while loop(for next row in 2d vector) and start for looping again.
Given this statement, the only way to print the output is when the if statements are true on the first iteration of their corresponding for loop. Put another way, if the if statement is false on the first iteration of any loop, then you say you need to return to the while loop and start again.

A little rewrite is dead on for what I'm trying to do. Here it is:
Given this statement, only print the output when the if statements are true on every iteration of their corresponding for loop. Put another way, if the if statement is false on any iteration of any loop, then there is NO output printed, and you need to ++a and return to the while loop and start again.
That is spot on dhayden!!!

I'll give better examples in a little bit.
I have included some code which should shed some light on this subject. I have used some details as to what I'm trying to iterate over and some examples of IF statement conditions. This is how I want/tried to accomplish this.

There are 4 For loops with an IF statement for each. I will describe things this way:
If each FOR loop iterates all the way through and the IF statement is TRUE through each iteration. Let's consider the FOR loop has PASSED!
If at any point through a FOR loops iteration, the IF statement is FALSE. Let's consider the FOR loop has FAILED.

Here is a great example, I HOPE!!
So, Loop#1 has Passed.
Loop #2 has Passed.
Loop #3 has Passed.
Loop #4 has Passed.
We then PRINT output (cout).
Increment the While loop with the (++a).
Then start looping again.

Next example:
Loop#1 has Passed.
Loop#2 has FAILED.
DON"T process Loops #3 or #4.
Don't print the cout.
DO Increment the While loop with the ++a.
Then start looping again.

Now, bear in mind, I'm not saying this code/method is the way of going about this. I initially thought using FOR loops with continue and break was correct. Obviously, I was not correct!! As you'll see, the FOR loops iterate over sometimes different vectors and 2dvectors. That's why I thought of using FOR loops in general. Anyway, here is some code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    int a {0};
    while (a < p5.size){  //  used to cycle through each row in 2d vector named p5 .
        for ( int b {0} ; b < (b + 65; ++b ) {  // Loop#1 - 65 iterations
            if ( p5vec1[a] != vec1[b] ) 

            break;
        }
        for ( int b = 100; b < (b + 35); ++b ) {  // Loop #2 - 35 iterations
            if ( p5vec2d_1[a][0] != vec2d_1[b][0] )
                
            break;
        }
        for ( int b = 100; b < (b + 44); ++b ) {  // Loop #3 - 44 iterations
            if ( p5vec2d_1[a][1] != vec2d_1[b][1] )
                
            break;
        }
         for ( int b = 50 ; b < (b + 24; ++b ) {  // Loop#4 - 24 iterations
            if ( p5vec2[a] != vec2[b] ) 

            break;
        }
        //  This cout gets executed if every IF statement retuns TRUE for EVERY iteration of its corresponding FOR loop, AND 
        //  ALL FOR loops have been iterated over.
        std::cout << p5[a][0] << " " << p5[a][1] << " " << p5[a][2] << " " << p5[a][3] << " " << p5[a][4] << endl;
    ++a;
    }
Well you wouldn't do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
	int a {0};

	while (a < p5.size) {  //  used to cycle through each row in 2d vector named p5 .
		for (int b {0}; b < (b + 65); ++b)  // Loop#1 - 65 iterations
			if (p5vec1[a] != vec1[b]) goto again;

		for (int b = 100; b < (b + 35); ++b)  // Loop #2 - 35 iterations
			if (p5vec2d_1[a][0] != vec2d_1[b][0]) goto again;

		for (int b = 100; b < (b + 44); ++b)  // Loop #3 - 44 iterations
			if (p5vec2d_1[a][1] != vec2d_1[b][1]) goto again;

		for (int b = 50; b < (b + 24); ++b)  // Loop#4 - 24 iterations
			if (p5vec2[a] != vec2[b]) goto again;

		//  This cout gets executed if every IF statement retuns TRUE for EVERY iteration of its corresponding FOR loop, AND
		//  ALL FOR loops have been iterated over.
		std::cout << p5[a][0] << " " << p5[a][1] << " " << p5[a][2] << " " << p5[a][3] << " " << p5[a][4] << endl;

	again: ++a;
	}


that wouldn't be good coding.
Thanks for the further explanation. It really helps.

I think you don't want nested loops at all. It sounds like you want these loops to run sequentially, one after the other:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void f()
{
    while (a < t5.size) {
	func();
	++a;
    }
}

void f()
{
    // Run the first for loop. If the condition ever fails that you're done.
    for (x=0; x<i; ++x) {
	if (!condition) return;
    }


    // Now run the second for loop:
    for (x=0; x<j; ++x) {	  // loop thru something for 'i' times
	if (!condition) return;
    }

    // etc.

    // If you get here then all conditions were met
    std::cout << "Line No. " << a << " has passed criteria" << std::endl;
}

seeplus:
Nice to hear from you again. You helped me out and gave me some confidence in my first post in this forum.
Well you wouldn't do it like this:
Yeah, I was just using that layout/way for easy explanation purposes. I made some mistakes in this thread explaining myself. I was just looking for something easy to follow and with better detail.
that wouldn't be good coding.
As I'm learning, it seems to me, that code I'm writing is not good coding. This C++ is not an easy task for me. I'm trying though, and won't give up! Thanks for popping in here. It is nice to hear from you again.

dhayden:
Thanks for the further explanation. It really helps.
You can't imagine how relieved I am to hear that!! Sometimes I do have a hard time putting my thoughts into written words. I also thought that what I initially asked was a simple question. Believe me......I had NO IDEA what I was asking about!!! Thanks for your replies and help!!! Greatly appreciate it!!! On to the functions....

It's kind of ironic that the functions are the way to go for this. I have only written 1 successfully other than in my course material. The second function I tried, kept giving me errors about (a 2d vector) t5 is not declared in this scope. So, I'm currently reviewing the course section on functions. Its frustrating when you think you understand something, and try it on your own, just to find out, YOU HAVE NOT A CLUE WHAT YOU"RE DOING!! That has been almost everything I tried to do. Still, I'm not ready to throw in the towel!

The function examples that you posted look much better than the nesting loops I wrote. I will give that a try!! I do have 2 questions about it though.
#1 - On line 9 should that read void func ()? I see that on line #1 its void f () and (If I'm correct) it looks like the function on line1 calls the function on line 9. If that is not the case, can you educate me on what is happening there.

#2 -
if (!condition) return;
I don't understand the return on the same line as the IF statement.
Line 9 should be func(), not f(). Note that the key here is func(). The code in f() could just as easily be inside main().

if (!condition) return;
This is the same as
1
2
if (!condition)
    return;

I just put it all on one line. In C++, newlines are usually the same as spaces (and tabs).
MANY THANKS dhayden!!!!!!!!!

I understand. I will be giving this a try later tonight. If it works as planned, I'll be the one doing backflips!! Oh wait......I don't know how to do them either. I better stick to learning one thing at a time. Thanks again!!

Brian
Pages: 12