0

Below you have two different codes. The difference between the two is simply for the variable sum, sum was initialized compared to giving sum the value 0 sum =0;

#include <iostream>
using namespace std;
int main(){
    
    //This code will display first ten numbers and get the sum of it
    cout << "The natural numbers are: " << endl;
     for(int i=1; i<=10; i++)
     {
         cout << i << " ";
         
     }
    cout << endl;
// variable was initialized 
    int sum;
    cout << "The sum of first 10 natural numbers: ";
    for(int i=1; i<=10; i++)
      {
          sum = sum +i;
      }
    cout << sum;

    cout << endl;
    
}

This Code outputs:

The natural numbers are: 1 2 3 4 5 6 7 8 9 10

The sum of first 10 natural numbers: 32821

Program ended with exit code: 0

#include <iostream>
using namespace std;
int main(){
    //This code will display first ten numbers and get the sum of it
    cout << "The natural numbers are: " << endl;
     for(int i=1; i<=10; i++)
     {
         cout << i << " ";
         
     }
    cout << endl;
// here I gave the value 1... this time it worked
    int sum =0;
    cout << "The sum of first 10 natural numbers: ";
    for(int i=1; i<=10; i++)
      {
          sum = sum +i;
      }
    cout << sum;

    cout << endl;
    
}

This Code outputs:

The natural numbers are: 1 2 3 4 5 6 7 8 9 10

The sum of first 10 natural numbers: 55

Program ended with exit code: 0

Why does the code do this? Can someone please explain to me why they gave me two different sums?

Kyoshi N
  • 3
  • 3
  • 1
    `// variable was initialized` this is not true comment to the statement `int sum;` and here you `// here I gave the value 1` to the statement `int sum =0;`. – 273K Aug 02 '20 at 16:30

4 Answers4

4

If you do not initialize sum it has an indeterminate value and there's no way you can tell what operations on it will do. Reading an uninitialized variable is undefined behaviour and doing so renders your entire program invalid.

Btw; you seem to be confused about what initialization is. int sum; does not initialize sum, it just declares it - it does not give it an initial value and you may not read it or use it in computations until you have assigned it a known value. int sum = 0; does initialize sum - that is, it gives it an initial value and you can now validly read it and use it in computations.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Good answer, but note that this answer uses words that mean things in C++ in an English sense that runs contrary to their C++ meaning. In C++, `int sum;` is an initializing declaration and the variable is initialized, same as if you wrote `T sum;` for some other type `T`. But, here, the initialization is default-initialization which itself "performs no initialization" and the storage contains an indeterminate value and you cannot use it. – Jeff Garrett Aug 02 '20 at 19:03
  • @JesperJuhl I didn't mean to offend. I was just trying to clarify since it could be confusing, particularly to a new person to the language, to reconcile this answer with the true statements that `sum` in `int sum;` is initialized when the declaration is executed and that this declaration is an initializing declaration. It's a good answer (you have my upvote), very clear and using the natural meaning of the words (C++ just doesn't always use the natural meaning of words). – Jeff Garrett Aug 02 '20 at 20:19
  • @JeffGarrett "I didn't mean to offend" - You didn't. – Jesper Juhl Aug 06 '20 at 16:15
0

Activate the compiler flag -Wuninitialized.

In the first program, the sum is kept uninitialized and contained garbage value. Thus, you get the error. OTOH, in the second program, the value of sum is initialized to 0, which is exactly a zero and thus, the count did successful.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
0

When you write int sum; in c++, a space in the memory is reserved for this variable, because it's not only a declaration, but also a definition. As sum is not set to any value yet, then, in this case, it gets any crazy value stored in it's space of memory that was already stored there before. Hope it helped :) Here are some useful links about this: link1; link2

claricetorres
  • 128
  • 1
  • 8
  • `[…]As sum is not set to any value yet, then it gets any crazy value stored in it's space of memory that was already stored there before[…]` while this might be true in many cases, is, in fact, undefined behavior if you read from it. This means that form that point the program is in an invalid state, and anything after that point could fail. In the best case, you only get an unpredictable value, in the worst-case anything code after that point misbehaves even if it is valid. – t.niese Aug 02 '20 at 17:35
  • Yes, that's what happens. :) – claricetorres Aug 02 '20 at 17:54
  • Again, your explanation of what happens, in this case, might be true for a certain compiler, but that's not guaranteed. It is undefined behavior, so it could result in anything, the code could also just crash before printing anything or do something completely different. – t.niese Aug 02 '20 at 18:17
  • Oh, got it. Didn't know it could behave like that for others compilers. I knew it was unstable and that it's bc of this memory thing but some compilers could entirely reject this try then? – claricetorres Aug 02 '20 at 23:58
0

Actually in the first set of code the compiler took a random value of variable sum. In your case I think the compiler took value of of sum as 32766. This value 32766 is "garbage value".

So see in second case you gave sum a initial value hence compiler knows that user has given a value. So accordingly it will perform your given operation. Inside the loop sum will start from 0 and keep performing the given operation until it exit the loop. The operation for this Case2 codes is given below :

    sum = sum + i; //(here value of "i" increase by 1 with iteration of the given loop)
   /* 1 = 0 + 1
    3 = 1 + 2
    6 = 3 + 3
    10 = 6 + 4
    15 = 10 + 5
    21 = 15 + 6
    28 = 21 + 7
    36 = 28 + 8
    45 = 36 + 9
    55 = 45 + 10
    As you can see the value of "sum" after the loop is 55
    */

But in first case you didn't give sum initial value, so compiler don't know whether the value of sum is 0, 6, 15, 7 or 10. So, compiler took a random value for it, in your case it is 32766. Inside the loop it start from 32766 and continue its given operation. The operation for the Case1 codes see below :-

   sum = sum + i; //(like previous case here too value of "i" increase by 1 with iteration of the given loop)
    /* 32767 = 32766 + 1
    32769 = 32767 + 2
    32772 = 32769 + 3
    32776 = 32772 + 4
    32781 = 32776 + 5
    32787 = 32781 + 6
    32794 = 32787 + 7
    32802 = 32794 + 8
    32811 = 32802 + 9
    32821 = 32811 + 10
    Here you can see the value of "sum" after the operation is 32821
    */

Okay! summing up everything, your logic and code looks fine to me but in first case the value of sum was allotted by compiler randomly, so here everything went wrong for the first case.