Michael Michael - 1 month ago 9
C++ Question

what is the role of the comma in below statements?

Currently reading into PETSc when I came up to this syntax in C/C++:

PetscInt i, n = 10, col[3], its;
PetscScalar neg_one = -1.0, one = 1.0, value[3];

I do not understand the meaning of the commas here. Has it to do with tuples? Or is there something overloaded?


That's just declaring multiple variables of the same types.

It's like

int a, b;

The first line declares four variables of the type PetscInt, called i, n (which is initialized to 10), the array col[3] and finally its. The second line declares three variables of the type PetscScalar.

So this:

PetscInt i,n = 10,col[3],its;

is the same as:

PetscInt i;
PetscInt n = 10;
PetscInt col[3];
PetscInt its;

Some find the original way shorter, easier to type, and also nice since it shows that the variables share (part of) the same type. Some find it confusing and/or error-prone, this is subjective of course but I felt I should mention it to kind of motivate why you often find code like this.