简体   繁体   中英

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?

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.

In C++ you can't pass arrays by value. You are always passing a pointer to the first element. That is why you can switch from foo(int a[]) to foo(int * a) without breaking the code.

Example: Some IDEs create main functions like this: int main(int argc, char * argv[]) others as int main(int argc, char ** argv) .

You may take a look at Why can't we pass arrays to function by value? This explains it very well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM