Difference between while (guess) and while (!guess)

closed account (jh5jz8AR)
I am fresh to this forum and have been studying C++ on my own time after work.

I had a question about while loops.

I was going through my book and it shows a flag-controlled while loop.

for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
found = false;

while (!found)
{
    .
    .
    .
    if (expression)
        found = true;
    .
    .
    .
}


Is there a reason we can not do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
found = true;

while (found)
{
    . 
    .
    .
    if (expression)
        found = false;
    .
    .
    .
}


I appreciate the time you have taken to look this over and explain the reasoning behind this.

- Kennith
Last edited on
The reason they picked the former over the latter is because the variable name is found. If it was called searching/finding/notFound then the latter would make more sense.

ps while(!found) is the same as while(found == false) same with while(found) is the same as while(found == true)
Last edited on
Hey Kennith,

why do you think the second piece of code doesn't work? The meaning is just different.
How would you know, if you already found something ahead of time? Maybe something like this would make more sence:
1
2
3
4
5
6
7
8
9
valid = true;

while (valid)
{
    //...
    if (expression)
        valid = false;
    //....
}

'!' is logical negation. Basically, if you say "!expression" it is equivalent to "not expression". You can apply it to any expression which will evaluate as boolean.

So:

(1 == 2) == false
!(1 == 2) == true
!true == false
!false == true
...


Does that answer your question?
closed account (jh5jz8AR)
Hey giblit and bugbyte,

Thanks for the insight. I appreciate the clarification.
Topic archived. No new replies allowed.