Search code examples
c++pass-by-referencepass-by-value

C ++ pass by reference or pass by value?


So I thought that C++ works by value, except if you use pointers.

Although today I wrote this piece of code which works in a different manner than expected:

#include <iostream>

using namespace std;

void bubbleSort(int A[],int arrSize);

bool binarySearch(int B[],int key,int arrSize2);

int main(){
    int numberArr[10] = {7,5,3,9,12,34,24,55,99,77};
    bool found;
    int key;


    bubbleSort(numberArr,10);
    /**
    uncomment this piece of code
        for(int i=0; i<10; i++){
        cout<<numberArr[i]<<endl;       
    }

    **/


    cout<<"Give me the key: ";
    cin>>key;

    found=binarySearch(numberArr,key,10);

    cout<<found;
}

void bubbleSort(int A[],int arrSize){
    int temp;

        for(int i=0; i<arrSize-1; i++){
        for(int j=i+1; j<10; j++){
            if(A[i]>A[j]){
                temp=A[i];
                A[i]=A[j];
                A[j]=temp;
            }
        }
    }
}



bool binarySearch(int B[],int key,int arrSize2){
    int i=0;
    bool found=false;

    while(i<arrSize2 && !found){
    if(B[i]==key)
    found=true;
    i++;
    }


    return found;
}

When running this it seems that the values in numberArr are changing (sorted) in the main() function as well, just uncomment the commented block.

Any thoughts on why are the values of numberArr changing in main function as well?


Solution

  • int[] as a type is essentially still a pointer due to array decaying. Therefore, you are passing an array "reference" (as in a value that will be used to "pass-by-reference", not as in an actual C++ reference like int&) and not a "value."

    The "value" of int[] or int* itself is still "pass-by-value," it's just that the value is being used to access the "pointed-at" object memory by reference.