return -1

Please, in short and clear (even for me:d) what actually means : return -1?

Many thanks!!!
Return is used to pass a value back from a function to wherever it was called from.
http://www.cplusplus.com/doc/tutorial/functions/

If it is used in main(), then the value is passed to the operating system when the program ends. Usually the value is ignored, but can be used in a script to determine whether or not the program ran properly, and to decide what action to take next.
Last edited on
In the code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

int FindLinear(int array[],int value, int key){

for (int i=0; i<value;i ++)

{
    if (array[i]==key)
    return i;
}

return -1
}

int main(){
const int x=10;
int evens[x];
  

for (int i=0;i<x;i++)
evens[i]=2*i;

int keyy, result;
do
{
cout<<"Input key: "<<endl;
cin>>key;


if (key!=0)
{
result=FindLinear(evens, x, key);
if (result!!=-1)
cout<<"Searched value in in the array"<<endl;
else 

cout<<"Searched value is NOT in the array."<<endl;
}

}
while (key!=0);
return 0;
}



So, could we put any other number instead of -1 in that: return -1?

(because we are obviously using it only for if-if)?

Could we even put anything else that number ( avariable? declared before, not infvolving the result?)


Many thanks!
Since you've declared FindLinear to return an int, you can return any int value you like.

The point of the return statement is so that the function can pass back some kind of information to the code that called it. So as long as the calling code can interpret that value in a useful fashion, return whatever value you want.
In this function:
1
2
3
4
5
6
7
8
9
10
int FindLinear(int array[], int value, int key)
{
    for (int i=0; i<value; i++)
    {
        if (array[i]==key)
        return i;
    }

    return -1
}

value is really the size of the array.
key is the value to search for.

The for loop checks each element in the array to see whether it matches the key. If a match is found, the value of i is returned immediately, without any need to continue with the rest of the loop.

Since the array size is given by value, a successful search will result in a value of i in the range 0 to value-1. For example, if the array size is 10, a valid result would be in the range 0 to 9.

In order to indicate that the search has failed, when the for loop reaches the end without finding the key, the value -1 is returned. This is convenient, because any valid result must be a positive number, so a negative number is used to show that it has failed. The particular value -1 is a good idea as it shows clearly a specific meaning.
Topic archived. No new replies allowed.