mercredi 29 juin 2016

Passing by reference and returning by (bool or reference)?


There are two ways to achieve the same behavior: Passing an array to the function, wait till read and write operations on array are done, then go on from where the function was called.
Originally I returned an array created inside Func which is undefined behavior. So whats the better way having these two options (if good at all):

typedef int array[100];
array& Func1(int (&array)[100]) {// option 1
    // read write on array
    return array;
}

bool Func2(int (&array)[100]) {// option 2
    // read write on array
    return true;
}

int main() {
    int a[100];
    a = Func(a);// fail
    if (Func(a)) { 
        //continue 
    }

}

Update
With the typedef I manage to return arrays, but as theyre not assignable I should use a vector as pointed out in the comments.
So it boils down to: How to make sure Func3 returns before Func4 starts.

//use refrence to prevent decay to pointer (sizeof etc.)
void Func3(int (&array)[100]) {// option 3
    // read write on array, takes long
}

void Func4(int (&array)[100]) {// option 4
    // read write on array modified by Func3
}

int main() {
    int a[100];
    Func3(a);
    Func4(a);

}

Also the caller needs the function to finish before he can continue.


Aucun commentaire:

Enregistrer un commentaire