dimanche 26 février 2017

Printing a variable without assigning a value

In C++, what happens if I print a variable that has not been assigned a value? The following two code gives me two different result. Also, the first one gives different result in each compilation and second one prints 0 everytim. Why?

int main() {
    int x = 1;
    int y;   // No value has been assigned
    if (x) {
        cout << y;    // without using endl
        // prints different value each time
    }
}

vs.

int main() {
    int x = 1;
    int y;   // y is not initialized
    if (x) {
        cout << y << endl;    // using endl
        // prints 0
    }
}

Aucun commentaire:

Enregistrer un commentaire