Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this conditional parsed?

Tags:

c++

For some context, the conditional is used in the normal type of algorithm for finding linked list cycles:

From link: http://vijayinterviewquestions.blogspot.com/2007/05/how-would-you-detect-loop-in-linked.html

p=head;
q=head->next;

while(p!=NULL && q!=NULL) {
    if(p==q) { //Loop detected! exit(0); }

    p=p->next;
    q=(q->next)?(q->next->next):q->next;
}

// No loop.

What does the line:

q=(q->next)?(q->next->next):q->next;

get parsed as though? I'm a little confused about operator precedence in this conditional - does q take the value of the left hand side of the ? or of the whole conditional?

like image 754
John Humphreys Avatar asked Dec 27 '22 13:12

John Humphreys


1 Answers

that can be expanded to:

if (q->next) {
  q = q->next->next;
} else {
  q = q->next;
}
like image 191
K Mehta Avatar answered Jan 18 '23 17:01

K Mehta