Search code examples
c++performancepointers

Is there a more efficient way to modify an array's contents within a function when only given a pointer to the first element?


I am simply wondering if there is a more efficient way to implement a function as opposed to the way I have done it. The constraints of the function are that the parameters MUST remain the same, and I can only edit what lies within the function. Here is my code:

void function_four(int* arr, int size, int& lowest, int& highest){
    lowest = *arr + 2;
    highest = *arr + 2;
    for(int i = 0; i < size; i++){
        int* valptr = arr+i;
        *valptr += 2;
        int val = *valptr;
        if(val > highest){
            highest = val;
        }

        if(val < lowest){
            lowest = val;
        }
        
    }
}

The purpose of this function is to update every value within the array by adding two.

Although this solution works, I am simply curious to know if a better solution exists without changing the function parameters.

At first, I had two different for loops: one for updating each array value, and another for finding the min/max values in the array. However, I merged them together in order to decrease runtime. Any other fixes would be greatly appreciated.

Thank you!


Solution

  • The biggest issue in your code isn't the array, but the reads from and writes back to highest and lowest. The compiler in general cannot prove whether highest and lowest alias some members of arr, especially given the unbound size.

    That is to say, *valptr += 2; could change lowest or highest, and highest = val could change any element of arr[]. The aliasing works both ways.

    Therefore, the easy fix here is to store the two results in local variables, and only update highest and lowest after the loop. The compiler can easily prove that these two local variables do not alias arr, precisely since they're local.