简体   繁体   中英

Boolean variable is changing and I don't know why — C language

I have written a main function to test searchRecursive, which takes a value (to search for), an array, and an int that represents the size of the array. When running the code below, the value of found is false. I don't understand this. The #2 is clearly in the array below so it SHOULD return true.

The results from running the program:

This should return true
0

If you take a look at the results from running this program above, you will see the block is reached where it should return true, but it's printing a 0 from main function which means it's false.

bool found = false;

int main(void)
{
    int values[5]={1,2,3,4,5};

    found = (search (2, values, 5));
    printf("%d\n", found);      
}

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{

    // if int isn't positive, return false
    if (n < 0)
    {
        return false;
    }
    else
    {   
      return (searchRecursive(value, values, n));
    }
}

bool searchRecursive(int value, int values[], int n)
{
    // if the first value of array matches the value, return true
    if (values[0] == value)
    {
        return true;
    }

    // if the first value of the array doesn't match the value and the 
    //   length is 1, return false
    else if ((values[0] != value && n==1) || n<1)
    {
        return false;
    }

    // if n is greater than 1 and value is greater than midpoint, divide 
    //   array, reassign value of n and call searchRecursive
    else if (n > 1) 
    {
        int midpoint = n/2;
        int newSize = midpoint;

        if (value == values[midpoint])
        {
            printf("This should return true\n");
            return true;
        }

        else if (value > values[midpoint])
        {
            int array[midpoint-1];

            for (int x=0; x < newSize; x++)
            {
                array[x] = values[midpoint + 1];
                midpoint++;
            }

            searchRecursive(value, array, midpoint);
        }

        else if (value < values[midpoint])
        {
            int array[midpoint];

            for (int x=0; x < midpoint; x++)
            {
                array[x] = values[x];
            }              

            searchRecursive(value, array, midpoint);
        }
        else
        {
            return false;
        }   
    }
    else
    {
        return false;
    }
        return false;      
}

Change these lines

searchRecursive(value, array, midpoint);

to

return searchRecursive(value, array, midpoint);

You must return the result of the recursive calls.

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