Operator precedence in C++

Viewed 184

For the following function

int search(int n) {
    return arr[n] == n ? n : arr[n] = search(arr[n]);
}

Not very sure exactly what it's supposed to do. According to what I understand about operator precedence, my guess is that 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?

1 Answers

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 SO 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 throw a StackOverflow exception!
For Example: arr[2] = {1,0}; and search(1);.

Related