hello everyone I'm puzzled why this function returns 0 every time. I use arr[0] as index and define it size of array in main func.
int sum_array (int arr[]) {
int result;
arr[0] = arr[0]-1;
if(arr[0]<=0){
return 0;
}
result = ((sum_array(arr))+(arr[arr[0]]));
return result;
}
If I use if(arr[0]<=1) instead of if(arr[0]<=0) it returns 5. I also don't get why it returns 5.
array = {0,1,1,2,3,3,4}
result=((sum_array(arr))+(arr[arr[0]]));exhibits undefined behaviour because the result is dependant on the evaulation order of+as the left side modifiesarr[0]and the right side reads the same value. Your program is ill-formed. Therefore the compiler is under no obligation to output anything sensible.ifstatement will be true in the first call and any subsequent call as well.