What is " int x,y,z = 1 " doing, if not assigning 1 to each?

Viewed 445

I am new to C/C++ and I noticed my program calculating wrong values. I found the problem to be my understanding of how the declaration of variables works in C/C++. x,y,z = 1,2,3 works fine in Python where as x,y,z = 1 does not. int x,y,z = 1,2,3 doesnt not work in C/C++ but int x,y,z = 1 does, kind of, since cout << x; outputs 16 and I expected it to be 1.

#include <iostream>
using namespace std;

int main() {

    int x, y, z = 1;
    cout << x;
    
    return 0;

}

// The output is 16

What is the operation int x,y,z = 1 doing, if not assigning 1 to each?

2 Answers

It is shorthand for:

int x;
int y;
int z = 1;

x and y are left unassigned.

int x,y,z = 1 initializes ONLY z to 1, x and y are left uninitialized.

Related