Home > Blockchain >  For Loop is not iterating for a third time? (C )
For Loop is not iterating for a third time? (C )

Time:12-15

Question: Why is my for loop not iterating for the third time?

What I noticed: In the for loop statement below, removing the if-else statement allowed me to print i from 0-2 and the "1" three times.

for (size_t i {0}; i < user_input.length();   i) {
        
        cout << i << endl;
        cout << user_input.length() << endl;
        
        string the_spaces;
        string the_line;

        for (size_t b {i}; b < (user_input.length() - 1);   b) {
            the_spaces  = " ";
        }

        for (size_t k {0}, y {i 1}; k < y;   k) {
            the_line  = user_input[k];
        }
        
        if (i >= 1) {
            cout << "Bob";
            for (size_t z {i - 1}; z >= 0; --z) {
                the_line  = user_input[z];
            }
        }
        else {
            cout << "Beb" << endl;
        }
        
        cout << "1" << endl;
            
    } 

Output:

0                   // i
3                   // the user_input.length
Beb                 // output from if-else
1                   // 1 printed at the end of the for loop expression
1                   // i (2nd iteration)
3                   // the user input.length 

the code ends here... Neither printing Beb or Bob, as well as, the "1" from cout << "1" << endl; on the 2nd & 3rd iteration.

CodePudding user response:

z >= 0 is always true since z is an unsigned type.

Your program therefore loops. Although there are other solutions, using a long long rather than a std::size_t as the loop index is probably the simplest.


b < (user_input.length() - 1) is also problematic if user_input is empty. Use

b   1 < user_input.length()

instead.

CodePudding user response:

In the for loop:

for (size_t z {i - 1}; z >= 0; --z) {
    the_line  = user_input[z];
}

because size_t will never be negative, so z >= 0 will always true. So this is an infinite loop.

You can typecast it:

for (long long z {static_cast<long long>(i - 1)}; z >= 0; --z) {
    the_line  = user_input[z];
}

or if you don't want t typecast it, you can use this rather odd way:

for (size_t z{i}; z-- > 0; )
    the_line  = user_input[z];
}

CodePudding user response:

One addition to the answers already given: Another C standard conform and highly portable signed type appropriate for z is std::ptrdiff_t. (It is similar to POSIX's ssize_t.)

(Quoting from the standard: "std::ptrdiff_t is used for pointer arithmetic and array indexing, if negative values are possible.")

  • Related