3

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?

1

1 Answer 1

5

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

5
  • My interpretation was incorrect. I deleted my answer.
    – R Sahu
    Commented Oct 25, 2019 at 20:45
  • Actually arr is created via for (int i = 1; i <= d; ++i) arr[i] = i somewhere else in the code so there wouldn't be a case of endless recursion
    – jafuweze
    Commented Oct 25, 2019 at 21:24
  • Okay further down the code I see arr[search(a)] = search(b) so I'm not so sure now...
    – jafuweze
    Commented Oct 25, 2019 at 21:26
  • Does a stack overflow throw an exception in C++? Isn't it undefined behaviour? Commented Jun 6, 2024 at 13:56
  • @PeterMortensen, maybe that's the more correct thing to say. I recall when I wrote this answer I did see an "exception" thrown in the Visual Studio debugger. So maybe the exception is just MS VC++ specific.
    – Romen
    Commented Jun 6, 2024 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.