Reputation: 9
I am supposed to write a program that has an array of 20 integers and it needs to call a function that uses a linear search algorithm to locate one of the values and another function that uses a binary search algorithm to locate the same value. Both functions need to keep count of the number of comparisons it makes and display them.
I need to use the following prototypes :
int linearSearch(const int arr[], int size, int value)
int binarySearch(const int array[], int numElems, int value)
Once I compiled the program I get a warning that states
variable 'position1' set but not used".
I have initialized the variable but I am unable to find the problem.
//Function for linear search
int linearSearch(const int arr[], int size, int value)
{
int index = 0;
int position1 = -1;
bool found = false;
int counter1 = 0;
while( index < size && !found)
{
if(arr[index] == value)
{
found = true;
position1 = index;
}
index ++;
counter1++;
}
return counter1;
}
Upvotes: 0
Views: 180
Reputation: 41750
The compiler is right. You never actually use position1
. Let's take a look at all the places you access to position1
:
//Function for linear search
//int linearSearch(const int arr[], int size, int value)
//{
// int index = 0;
int position1 = -1;
// bool found = false;
// int counter1 = 0;
//
// while( index < size && !found)
// {
// if(arr[index] == value)
// {
// found = true;
position1 = index;
// }
// index ++;
// counter1++;
// }
// return counter1;
//}
You initialize the value of position1
, then assign it with a potentially meaningful value calculated by position1 = index;
Now tell me: where do you read the value of position1
?
Nowhere in the function you actually read the value of position1
, nor do you return it's value. In fact, it's value could be 100000000
or -2
, your program will behave the same, since you never read the value. In fact, you could entirely remove the variable and your program will still behave exactly the same!
The compiler knows that because position1
is a local variable. The scope of the variable position1
is only within the function.
Upvotes: 1
Reputation: 3281
The compiler is just letting you know that you've declared a variable that is not being used. The program can still compile as it is a warning rather than a build time or run time error.
Upvotes: 0