-3
#include <bits/stdc++.h>

using namespace std;

int myfunc(int n, int m, int k, int arr[], int arr1[]) {

    int x = 0, y = 0;
    for (int i = 0; i < n; ++i) {
        if (arr[i] > k) {
            x += 1;
        }
    }

    for (int i = 0; i < m; ++i) {

        if (arr1[i] > k) {
            y += 1;
        }
    }

    return max(x, y); // why is this not working?

}
int main() {

    int n, m, k;

    int arr[n];

    int arr1[m];

    cin >> n >> m >> k;

    cout << "first: \n";

    for (int i = 0; i < n; ++i) {

        cin >> arr[i];
    }
    cout << "2nd arr\n";
    for (int i = 0; i < m; ++i) {
        cin >> arr1[i];
    }
    myfunc(n, m, k, arr, arr1);

    return 0;
}

In this code function is not returning any value but when I use cout<<max(x,y) instead of return max(x,y), it's working fine. Can anyone explain me why is this happening?

cigien
  • 50,328
  • 7
  • 37
  • 78
Keeto
  • 1
  • 1

1 Answers1

0

Your confusion seems to be arising from a misunderstanding of what it means to return a value from a function versus printing the value inside the function. Consider the following function that prints the right answer:

void f() 
{
  std::cout << 42;
}

Fine, this works and can be called like f();, and it prints the values.

On the other hand, if the function were to return a value, like this:

int f()
{
  return 42;
}

then simply calling the function f(); is not going to do anything because you are not using the returned value. Instead, you need to do something like:

std::cout << f();

From C++17, you can use an attribute for a function that returns a value, indicating that the returned value is meant to be used, and that not using it is a mistake:

[[nodiscard]] int f()
{
  return 42;
}

This has the nice property that a call like f(); will throw a warning, and the only way to avoid the warning is to actually use the returned value.

cigien
  • 50,328
  • 7
  • 37
  • 78