0

I was writing a very basic C++ code. I am takin 2 lines of inputs

First line -> number of integers: 1<N<10

Second line -> long integers separated by whitespace: 0< ar[i] < 10^10

Example input:

5
1000000001 1000000002 1000000003 1000000004 1000000005

My function should return the resultant value. Here it is:

long aVeryBigSum(vector<long> ar,int ar_count) {
    long result;
    for (int i = 0; i < ar_count; i++) {
        result = result + ar[i];
        cout << to_string(result) + "\n";
    }
    return result;

}

Output:

5000000015

It works fine with this way; however, when I comment out the "cout" line, it returns something gibberish:

140741662329871

I don't understand why that happens. I'd appreciate if someone could. Thanks in advance.

baymurat
  • 81
  • 5
  • 3
    You need to initialise `result` : `long result = 0;`. – Paul Sanders Feb 14 '21 at 18:48
  • You ought to get a warning from your compiler about the uninitialized variable. If you don't, figure out how to enable warnings from your compiler, or get a better one. – Nate Eldredge Feb 14 '21 at 18:50
  • @PaulSanders yeah that worked, but I want to learn why it didn't work in the first place and the thing we changed affected what and how it solved the problem? Moreover, what is the meaning of the gibberish answer, how did the pc calculated it? – baymurat Feb 14 '21 at 19:16
  • 1
    When you declare a variable without initializing it, its value will be what's in memory at that moment. Except for global and static variables, which are all initialized to zero at the beginning of the program – Jack Lilhammers Feb 14 '21 at 19:23
  • If you don’t initialize `result` it contains an indeterminate. And reading an indeterminate value is undefined behavior. – t.niese Feb 14 '21 at 20:00
  • 1
    @JackLilhammers `its value will be what's in memory at that moment` In the best case this is true. But according to the specs it holds an indeterminate value, and reading that results in undefined behavior. – t.niese Feb 14 '21 at 20:05
  • [Has C++ standard changed with respect to the use of indeterminate values and undefined behavior in C++14?](https://stackoverflow.com/questions/23415661/has-c-standard-changed-with-respect-to-the-use-of-indeterminate-values-and-und) – t.niese Feb 14 '21 at 20:13

0 Answers0