简体   繁体   中英

Logical error with the || operator?

A part of my program (I can add more details if necessary) contains this line:

if((e->start->explored = false) || (e->end->explored = false)){
   //do action...
 } 

This is part of a graph algorithm, where e is a directed edge with incident vertices "start" and "end." I would like the 'action' to happen if at least one of the incident vertices of e is unexplored, but this logic appears to be faulty. Although I used a small example and verified that, indeed, the start and end vertices of my edges were unexplored to start with, my overall function is going into an infinite loop.

So then I tested it like this:

  if((e->start->explored = false) || (e->end->explored = false)){
       //do action...
     } 

  else cout << "FAIL"; 

...and, of course, it printed a screen of "FAIL." What is my logic error here?

You're assigning false to your properties instead of testing them against false . This is a mistake often made, and quite hard to debug. Change your = assignment operator to the equality operator == :

if((e->start->explored == false) || (e->end->explored == false)) {
    // Do action...
} else {
    cout << "FAIL";
}

Instead of comparing the values to false , it's clearer to use the ! not operator instead. The inner brackets are done away with, too:

if(!e->start->explored || !e->end->explored) {
    // Do action...
} else {
    cout << "FAIL";
}

As the others have expounded you accidentally used assignment instead of comparison. However, the real solution is not to compare at all:

Comparing bool values to literals true and false is nonsensical!

Instead, write:

if(! e->start->explored || ! e->end->explored)

您已使用赋值运算符=而不是比较运算符==。

You are assigning values here:

if((e->start->explored = false) || (e->end->explored = false)){

Should be:

if((e->start->explored == false) || (e->end->explored == false)){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM