Assignment vs. Intialization

What is the difference between the two? How does unintializied variables cause bugs?
Initialization calls the constructor, assignment calls the = operator.
Classes always call a constructor on declaration, even if not explicitly coded. A lack of a default constructor will cause compiler error if none is called.

POD or basic types ( eg: int ) usually are not initialized if not explicitly so they will hold some garbage values which can result in unexpected behaviour of the program
It is a semantic difference, really. When we ask, for example, "what is variable x initialized to?" we are
asking what value x was originally set to (the first value given to x after x was instantiated). As a matter of good
programming practice, variables should be initialized at the time of instantiation. Example:

1
2
3
4
5
6
7
8
9
/* Good practice: */
int x = 5; 

/* Bad practice:*/
int x;  // x is instantiated here
cout << "Hello World" << endl;
DoSomeOtherStuff();
x = 5;  // x is "initialized" here 
cout << "The value of x is " << x << endl;


Notice in the above code that I write x = 5;. Yes, this is assigning a value to x, and so yes,
this is also an assignment.

What Bazzy says is also right.

How do uninitialized variables cause bugs?

Well,

1
2
3
4
5
6
int main() {
    char* p;   // uninitialized
    cout << "The string is: " << p << endl;    // potential crash due to accessing who knows what memory
    int x;  // uninitialized
    cout << "100/x = " << 100/x << endl;   // division by 0 exception if x happens to be zero.
}


etc.
Topic archived. No new replies allowed.