Home > Software design >  Why does my function always return 0 instead of returning the sum result?
Why does my function always return 0 instead of returning the sum result?

Time:09-23

I just started learning C , now I'm making a simple array sum function.

Why is my code output always 0? Does it mean that my function returns "0"?

If I put cout in the function, it shows the right sum result.

#include <iostream>
using namespace std;

int ArraySum(int arr[], int size){
  int sum=0;
  for(int i=0 ; i<size; i  ){
      cin >> arr[i];
      sum  =arr[i];
  }   
  return sum;
}
   
int main()
{
    int n, sum;
      cin >>n;
   int arr[n];
     ArraySum(arr, n);
   cout << sum;
    return 0;
}

CodePudding user response:

You are not assigning the return value to the sum when it is returned.

You have 2 options:

  • pass a pointer to the sum, and dereference it inside ArraySum()

  • assign the value that is returned by ArraySum() to the sum int.

CodePudding user response:

You forgot to assign ArraySum()'s return value to main()'s sum. As a result, main()'s sum is still uninitialized when you print it.

Change this:

ArraySum(arr, n);

to this:

sum = ArraySum(arr, n);

As a side note, you should know that this is not actually valid, standard C :

int arr[n];

This is a "variable-length array" ("VLA" for short.) This works on some C compilers because they support VLAs as an extension. But relying on compiler-specific extensions is not recommended if you want your code to be portable to any other C compiler.

Use std::vector instead. This also has the benefit of not needing to manually keep track of the size. vector knows its own size.

So, use this instead:

#include <iostream>
#include <vector>

// Note the '&' here. That means a reference of the vector is passed,
// not a copy, so the original vector defined in main() is used when
// assigning the values we read with `cin`.
int ArraySum(std::vector<int>& arr)
{
    int sum = 0;
    for (int i = 0; i < arr.size(); i  ) {
        std::cin >> arr[i];
        sum  = arr[i];
    }
    return sum;
}
   
int main()
{
    int n;
    int sum;

    std::cin >> n;
    std::vector<int> arr(n);
    sum = ArraySum(arr);
    std::cout << sum;
}

(Also note that in C , unlike C, there is no need to return 0 at the end of main(). It happens automatically.)

  • Related