Reputation: 13
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;
}
Upvotes: 1
Views: 850
Reputation: 51832
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 there is no need to return 0
at the end of main()
. It happens automatically. Keep in mind that this is only true for main()
. No other function that returns a value is allowed to omit the return
statement. main()
is a special case in this regard. But it doesn't hurt to return 0
anyway though. It's up to preference.)
Upvotes: 1
Reputation: 138
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.
Upvotes: 2