简体   繁体   中英

How to return boolean in a function?

I wanted to compare two arrays. I have set a variable as true and it gets false, when any element in an array does not match. I want to return that variable, which is a boolean, but it does not return that. Why is that?

bool compare_arr(int arr1[], int len_arr1, int arr2[] ,int len_arr2){
    cout << "Compare the two Arrays"<< endl;
    bool result = true;

    for(int x = 0; x < len_arr1; x++)
    {
        if(arr1[x]==arr2[x])
        {
            continue;   
        }
        else
        {
            result = false;
            break;
        }
    }
    
    return result;
}

int main()
{
    int arr1[] = {1,2,3,4};
    int len_arr1 = sizeof(arr1)/sizeof(arr1[0]);

    int arr2[] = {1,2,3,4};
    int len_arr2 = sizeof(arr2)/sizeof(arr1[0]);

    compare_arr(arr1,len_arr1,arr2,len_arr2);
        
    return 0;
}

You are not using the return value of the function call

compare_arr(arr1,len_arr1,arr2,len_arr2);

You could for example write

std::cout << compare_arr(arr1,len_arr1,arr2,len_arr2) << '\n';

or

#include <iomanip>

//...

std::cout << std::boolalpha << compare_arr(arr1,len_arr1,arr2,len_arr2) << '\n';

But in any case your function can invoke undefined behavior in case when numbers of elements in the arrays are different.

The function can be written simpler using the standard algorithm std::equal . For example

#include <algorithm>

//...

bool compare_arr( const int arr1[], size_t len_arr1, const int arr2[], size_t len_arr2 )
{
    return std::equal( arr1, arr1 + len_arr1, arr2, arr2 + len_arr2 );
}

Pay attention to that the type of the result of an expression with the sizeof operator is size_t . So you should write for example

size_t len_arr1 = sizeof(arr1)/sizeof(arr1[0]);
^^^^^^

Correspondingly the function parameters that specify the number of elements in the arrays should be also of the type size_t .

If you may not use standard algorithms then the function can be declared and defined the following way

bool compare_arr( const int arr1[], size_t len_arr1, const int arr2[], size_t len_arr2 )
{
    bool result = len_arr1 == len_arr2;

    for ( size_t i = 0; result && i < len_arr1; i++ )
    {
        result = arr1[i] == arr2[i];
    } 

    return result;
}

As David wrote you ignore the return value. You need to assign the return value to a variable to use it.

const bool compare_result = compare_arr(arr1,len_arr1,arr2,len_arr2);

Remarks on coding style:

You should fix your loop, as you only use the length of the first array, but if the second one would be smaller, you will get a seg fault.

And as you labelled the question as C++, think about using std::vector instead of c arrays.

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