What is the value of an initialised integer on its first use without explicit assignment?

Consider the following code:
int sum;
for(int i=0;i<n;i++)
{
sum+=arr[i];
}

Would sum be initialized with arr[i] on first use? Would it hold 0 on re-initialization?

See its the concept of storage classes. If you have declared a variable in the static storage class, which is done by either using keyword static or declaring it globally, then the initial value of variables is 0.
for example

#include<iostream>
using namespace std;
int arr[10];
int sum;
int main(){
  for(int i = 0; i < 10; ++i)sum+=arr[i];
  cout << sum;
}

is equivalent to

#include<iostream>
using namespace std;
int main(){
  static int sum, arr[10];
  for(int i = 0; i < 10; ++i)sum+=arr[i];
  cout << sum;
}

As both would produce the output of 0

But when register or automatic storage classes are used then they initially hold garbage value which can be really anything in range that computer hold. It’s all about luck and chance in that case.

#include<iostream>
using namespace std;
int main(){
  int sum, arr[10];
  //or register int sum, arr[10]'
  for(int i = 0; i < 10; ++i)sum+=arr[i];
  cout << sum;
}

this code will produce unexpected results, as garbage value, to some point, is random.

1 Like

@ay2306 CodeChef: Practical coding for everyone vs. CodeChef: Practical coding for everyone Is this the issue?

In 19880432 one at line 16, int sum is not initialized that means that sum will have a garbage value which is, to some point, random. Thus you whole code may behave randomly.
Now, that code might be working on your local system because of compilers and system can sometimes initialize variables in some cases. But since again this is unexpected behavior, so hence it’s all unexpected.

That is what I figured, thanks a lot.