-2

When i am this void linearSearch function in code with cout it is showing this error:

<source>: In function 'int main()':
<source>:28:10: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'void')
   28 |     cout << linearSearch(arr, n, key) << endl;
      |     ~~~~ ^~ ~~~~~~~~~~~~~~~~~~~~~~~~~
      |     |                   |
      |     |                   void
      |     std::ostream {aka std::basic_ostream<char>}

And when i write int linearSearch function with return it works fine.

#include <bits/stdc++.h>
using namespace std;

void linearSearch(int arr[], int n, int key)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == key)
        {
            cout << i;
        }
    }
    cout << "not found";
}
int main()
{
    int n;
    cin >> n;

    int arr[n];
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    int key;
    cin >> key;

    cout << linearSearch(arr, n, key) << endl;

    return 0;
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 3
    What do you think `cout << linearSearch(arr, n, key)` should output? – Drew Dormann Feb 02 '22 at 14:54
  • You should look what does it mean when you return 'void' from a function – Ezio Feb 02 '22 at 14:56
  • 2
    _"it is showing errors why?"_ The error message itself explains _why_. If you are asking what an error message means, please [edit] your question to include the error message you are asking about. – Drew Dormann Feb 02 '22 at 14:57
  • 1
    Sidenote: Get out of bad habits and read [Why should I not #include ?](https://stackoverflow.com/questions/31816095), [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721), [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097). Using all three in combination is a good way to introduce strange bugs. – Lukas-T Feb 02 '22 at 15:03
  • You cannot provide a `std::ostream& operator<<(std::ostream&, void);` stream inserter. – Eljay Feb 02 '22 at 15:15

1 Answers1

0

Your problem might be that you are trying to cout a function returning void. There is nothing for it to output. You might want to try either changing the linearSearch function to output a value or don't call

cout << linearSearch(arr, n, key) << endl;

Instead just call

linearSearch(arr, n, key);