strings in array question

i'm trying to find an occurrence of consecutive strings in a given array. b is supposed to be the position of the first string and e is supposed to be the position of the last string in the consecutive order of the strings...the compiler keeps telling me that this will only go through the loop once and i don't know why or how to fix that. also, i think my code is wrong but i don't know how to fix it to do what i want it to do. this is what i have so far inside bool stringOrder :

1
2
3
4
5
6
7
8
9
10
11
12
13
  int e;
    for (int i = 0; i < n; i++)
    {
        while  ((a[i] == type) || (a[i] == type && a[i + 1] == type))
        {
            int b = i;
            e += b;
            i++;
        }
        
        return true;
    }
    return false;


the compiler keeps telling me that this will only go through the loop once and i don't know why

Well, yeah. How many times do you think line 11 is going to be executed?
For the sake of clarity, let's remove the inner loop:
1
2
3
4
    for (int i = 0; i < n; i++)
    {  return true;
    }
    return false;

You will never execute more than one iteration of the outer loop.

You haven't shown the declarations for n, a or type, so I can only make assumptions about them.

line 4: You're evaluating a[i] == type twice. The second evaluation is pointless. if a[i] == type is true in the first evaluation, the right side of the || won't be evaluated. If a[i] == type is false, the right hand side of the conditional can never be true.

Line 4: Assuming n is the number of elements in the array, you're going to make an out of bounds reference evaluating a[i + 1] == type on the last iteration of the for loop.

Edit:
Line 1: e is an uninitialized variable (garbage).
Line 7: You're adding b to a garbage value.
Last edited on
Topic archived. No new replies allowed.