0

What is the default value, variables are assigned when they are not initialized? In the below code, i have not initialized variables - count and j however, i am getting different values. Won't all variables be assigned default value zero?Unable to understand.

#include<iostream>
#include<sstream>
using namespace std;

    int main()
    {
    char str[] ("Hello World!!!");
    char *p;
    int i;
    int count;
    int j;

    cout << "count is:" << count << endl;
    cout <<"Value of j is " << j <<endl;

    p=str;

    for (i=0;i<20;i++){
        cout << *p;
        p++;
    }

    cout << "Length of string is:" << count <<endl;

    }

o/p

count is:4198400 Value of j is:1 Hello World!!! Length of string is:4198400

Aisha
  • 11
  • 1
  • 7
  • 1
    "Won't all variables be assigned default value zero?" No, they won't. Why would you think they should be? –  Jan 11 '17 at 20:36

1 Answers1

1

Static variables are zero initialized, non-static variables are not initialised, and keeps the value that incidently is in memory at the location of the variable.

The reason why variables are not zero initialized is that it comes with a cost, it costs to initialize variables, and since C++ (and C) are high performance languages where you do not pay for what you do not use, they do not perform this initialisation.

Statics however are free to initialize, and are therefore zero initialized. This is one of the areas where the reason why it works like this in C++ is because it works like this in C, and C++ was thought of as a next iteration of C, and therefore keeps many of the same principles.

This is actually covered in the beginning of the Scott Meyers talk: "The last thing D needs"

int x;            //  x = uninitialized
int x;            // <-- in global scope: x = 0
static int x;     //  x = 0
int* x = new int; // *x = uninitialized
Tommy Andersen
  • 7,165
  • 1
  • 31
  • 50