I am learning to code in C++. I came across a problem that requires making a function to add up very large number and return the sum. I see a mysterious behavior. When I print the number veryBigSum
inside the function aVeryBigSum
before returning the value, it works properly.
#include <bits/stdc++.h>
#include <vector>
using namespace std;
long long aVeryBigSum(int n, vector <long long> ar) {
long long veryBigSum;
for(vector<long long>::iterator it = ar.begin(); it != ar.end(); ++it )
veryBigSum += *it;
cout << veryBigSum << "\n";
return veryBigSum;
}
int main() {
int n;
cin >> n;
vector<long long> ar(n);
for(int ar_i = 0; ar_i < n; ar_i++){
cin >> ar[ar_i];
}
long long result = aVeryBigSum(n, ar);
cout << result << endl;
return 0;
}
Input for the above is:
5
1000000001 1000000002 1000000003 1000000004 1000000005
Output for the above is:
5000000015
5000000015
But when I don't print the number inside the aVeryBigSum
function, the cout
statement inside main
displays some garbage value.
#include <bits/stdc++.h>
#include <vector>
using namespace std;
long long aVeryBigSum(int n, vector <long long> ar) {
long long veryBigSum;
for(vector<long long>::iterator it = ar.begin(); it != ar.end(); ++it )
veryBigSum += *it;
return veryBigSum;
}
int main() {
int n;
cin >> n;
vector<long long> ar(n);
for(int ar_i = 0; ar_i < n; ar_i++){
cin >> ar[ar_i];
}
long long result = aVeryBigSum(n, ar);
cout << result << endl;
return 0;
}
Input for the above is:
5
1000000001 1000000002 1000000003 1000000004 1000000005
Output for the above is:
5004197743
Can someone please explain to me why is this happening? I mean, how does printing a value affect passing of the variable between to function?