Radim Dolezal
Radim Dolezal

Reputation: 11

Passing an array of bools/ints to function which should alter it

I have defined an array of bools (also having version with array of ints - not sure what's better when i want to store just ones and zeros) in one function. How to pass it to a different function which is returning something else then that array? I'm trying with reference, but I'm getting errors..

bool functionWithAltering (bool &(Byte[]), int...){
    ...
}

bool functionWhereSetting (.....) {
    bool Byte[8];
    ....
    if (!functionWithAltering(Byte, ...))
         return 0;

    bool Byte[16];
    ....
    if (!functionWithAltering(Byte, ...))
         return 0;
    ...
}

The errors I'm getting are:

error: declaration of ‘byte’ as array of references
error: expected ‘)’ before ‘,’ token
error: expected unqualified-id before ‘int’

Thanks a lot for any suggestions!

Upvotes: 0

Views: 41

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

The correct declaration of a reference to an array will look the following way

bool functionWithAltering( bool ( &Byte )[8], int...){
    ...
}

Also instead of declaring the parameter as refernce to array you could use two parameters: pointer to array an its size

bool functionWithAltering( bool Byte[], size_t size,  int...){
    ...
}

Upvotes: 0

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

Just declare functionWithAltering like this:

bool functionWithAltering (bool Byte[], int...) {
    ...
}

Arrays in function arguments always decay into a pointer to the first element - they are never passed by copy, so you don't have to worry about possibly inefficient copies. This also means that any modifications to Byte[i] inside functionWithAltering() will always be seen by the caller.

As for your usage of the booleans array: if all you want to store is just 0 or 1, it's a perfectly valid and intelligent choice.

Upvotes: 1

Related Questions