Strange expression in return statement

I found a recursive function that surprised me a little, this function counts all the negative numbers that appear in the array:

int count_negative(int arr[], int n) { if ( n > 0 ) return (*arr < 0) + count_negative( ++arr, n - 1 ); return 0; } 

Can someone explain this line:

 return (*arr < 0) + count_negative( ++arr, n-1 ); 

thanks

+6
source share
3 answers

(*arr < 0) compares the first element of the array with zero. The result of the expression can be either 1 (the first element is negative) or 0 (the first element is positive or equal to zero). Thus, the number of negative elements is the sum of this expression and the number of negative elements in the tail of the array.

+6
source

*arr points to the first element of the arr array (or rather, the part of arr that was passed to the function in this particular call).

count_negative( ++arr, n-1 ) is a recursive call, but due to ++arr inside this call we count the next element of the array and the argument n-1 , togeher with if ( n > 0 ) guarantees that we will count only elements inside arr .

+3
source

The principle is that instead of storing the index on the element to be checked, since arr is a pointer and changing it will not change the data, instead, you can use arr as an iterator for the data in the array.

So, *arr < 0 checks if the current pointed element is negative (it will give 1 if yes, 0 if not), and ++arr increases the cursor to the next place in the array, which is then recursively passed to check the rest of the array.

This is a very famous idea in functional languages ​​that work with lists, where you often work on the first element of the list (head) and recursion in the remaining list (tail).

+2
source

Source: https://habr.com/ru/post/978239/


All Articles