Reputation: 7809
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?
Upvotes: 2
Views: 121
Reputation: 399881
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.
Upvotes: 12
Reputation: 134346
The commas here are just to declare multiple variables of the same type in a single line statement. You may very well break them into one individual line, each, like
PetscInt i;
PetscInt n = 10;
PetscInt col[3];
PetscInt its;
While both are valid and correct syntax, some of us prefer to use the broad version anyways, as it gives a better readability (IMHO) and avoid any possible confusion while having a pointer type or storage-class specifier associated with the type.
For example, for the shorthand
int * p, q;
is the same as
int *p;
int q; //not int *q
q
is not a pointer type there.
Upvotes: 4