Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence in C++

Tags:

c++

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?

like image 706
jafuweze Avatar asked Feb 16 '26 18:02

jafuweze


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 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);.

like image 99
Romen Avatar answered Feb 19 '26 06:02

Romen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!