And operator argument evaluation in C++ -


this question has answer here:

how , operator evaluates arguments. have code check whether graph cyclic or not. in code there , condition in if statement. , think, best of can make out is, terminates @ first encounter of false expression without evaluating second expression @ all.

this code

bool graph::iscyclicutil(int v, bool *visited, bool *recstack){     if (visited[v] == false){             // mark current node visited              visited[v] = true;             recstack[v] = true;              // recur vertices adjacent vertex             list<int>::iterator i;             (i = adj[v].begin(); != adj[v].end(); i++){      -------->**this , cond**if (!visited[*i] && iscyclicutil(*i, visited, recstack))                             return true;                     else if (recstack[*i])                             return true;             }     }     recstack[v] = false;    // remove vertex recursion stack     return false; }  void graph::printrecstack(bool *recstack){     cout << "\n \n";     (int = 0; < v; i++){             if (recstack[i])                     cout <<i<< "\n";     }     return; }   bool graph::iscyclic(){     // mark vertices not visited , not part of recursion stack     bool *visited = new bool[v];     bool *recstack = new bool[v];     (int = 0; i<v; i++){             visited[i] = false;             recstack[i] = false;     }      // call recursive helper function detect cycle in different     // dfs trees.     if (iscyclicutil(0,visited, recstack)){             printrecstack(recstack);             return true;     }     /*for (int = 0; < v; i++){             if (iscyclicutil(i, visited, recstack))                     printrecstack(recstack);                     return true;     }*/     return false; } 

please observe , condition inside if statement in iscyclicutil function.

if take simple graph test case one:

0->1 1->2 2->0 2->3 3->3 

and call iscyclicutil 0, first 3 values in recstack comes out true. should have not been case if second expression evaluated in if statement. because call node 2 reach child 0. since loop started 0, 0 visited, recstack[0] should initialized false. not happens, , of them come out true. if and condition terminated encountered visited[0] true, without calling iscyclicutil(0,visited,recstack) again.

that's correct. called short-circuiting , feature of many programming languages.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -