Reputation: 63
For the following function,
int search(int n) {
return arr[n] == n ? n : arr[n] = search(arr[n]);
}
I am not very sure exactly what it's supposed to do. According to what I understand about operator precedence, my guess is that the above is equivalent to
int search(int n) {
if (arr[n] == n) {
return n;
} else {
return arr[n] = search(arr[n]);
}
}
but then it doesn't really make sense to me that the function is returning an assignment? Or am I interpreting it wrong entirely?
Upvotes: 3
Views: 274
Reputation: 1766
Your expansion of the expression looks correct to me.
I think what you're missing is that assignment expressions can be evaluated as a value. The value returned is the value of the left operand after assignment.
So arr[n] = search(arr[n])
effectively returns arr[n]
after it was assigned the return value of search(arr[n])
.
This Stack Overflow answer covers the part of the standard that allows this and answers a similar question.
After testing some different initial arrays and arguments with that function, I should warn you that it can cause a stack overflow!
For example: arr[2] = {1,0};
and search(1);
.
Upvotes: 5