Help me understand this logic

I always have trouble with logic, even when it's simple. Here is a function designed to search an array for a value, and if the value is found, the loop will terminate:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int searchList(const int list[], int numElems, int value)
{
	int index = 0;
	int position = -1;
	bool found = false;
	while(index < numElems && !found)
	{

		if (list[index] == value)
		{
			found = true;
			position = index;
		}
		index++;
	}
	return position;
}

My problem in understanding is with the bool variable and the logical NOT. The bool is assigned false, which is also zero. So what is the loop condition saying? while(index is less than numElems AND NOTfalse) ? Saying while(NOT false) is the same as saying while(TRUE) . . . right? So the loop is saying, while(TRUE), continue looping. If it finds a matching value, then it assigns the found bool to TRUE, and then re evaluates the loop conditions which says, while(NOT false) or while(TRUE). Since the bool found, which was first assigned false, is now assigned true, and the while condition says to continue looping while true, shouldn't this be an infinite loop. I tried it in a program so I know it's not infinite-- it works, but I don't understand why?
My problem in understanding is with the bool variable and the logical NOT. The bool is assigned false, which is also zero. So what is the loop condition saying? while(index is less than numElems AND NOTfalse) ?

No. The loop condition is:
index is less than numElems and found is not true.
or, alternatively:
index is less than numElems and found is false.

The only time you know that found is false for sure is the very first time the condition is encountered. For following iterations, found may be either true or false, so no, it is not equivalent to "index is less than numElems and NOT false."


If it finds a matching value, then it assigns the found bool to TRUE, and then re evaluates the loop conditions which says, while(NOT false) or while(TRUE)

The condition is: while (index is less than numElems and found is not true). Since we've assigned found the value of true, this expression evaluates to false because found compares equal to true (or, put another way, !found is false.)


Since the bool found, which was first assigned false, is now assigned true, and the while condition says to continue looping while true, shouldn't this be an infinite loop.

Again, the loop continues while found is not true. Once found is true, the loop terminates.



Last edited on
Topic archived. No new replies allowed.