vendredi 24 février 2017

why "return 0" can bring back the parameter i assigned to function?

I'm a kind of new in C++. recently I learned how to return a pointer of array through function from C++ primer:

using arrT = int[10];
arrT* func(int i);

This code is suppose to define a function that would return a pointer that point to a array with ten ints. however, when I tried to use an array as the parameter, I found there is no directly way to return the pointer that point to the original array:

arrT* return_p(arrT arr){
    for(int i = 0; i < 10; ++i){
        *(arr+i) *= 2;
    }
    return arr;//error, can't convert int* to int (*)[10]
}

i know because here arr is converted and lost the array's dimension. However, I just found a way that works for me:

arrT* return_p(arrT arr){
    for(int i = 0; i < 10; ++i){
        *(arr+i) *= 2;
    }
    return 0; // return 0 is return pointer arr that point the first element of array arr.
}

I just wondering how did the return 0 work here? And I do have another result here if I use reference instead of using pointer:

arrT& return_r(arrT &arr){
    for(auto &i : arr){
        i *= 2;
    }
    return arr; // works, returned the reference to array named arr
}

but return 0 is not working for the reference version.

 arrT& return_r(arrT &arr){
    for(auto &i : arr){
        i *= 2;
    }
    return 0; // error, using an int rvalue to initialize a non_const that has type int(&)[10];
}

I hope I told my question clearly. thanks for your help!

Aucun commentaire:

Enregistrer un commentaire