2

C/C++ でこの構文にたどり着いたとき、現在 PETSc を読み込んでいます。

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

ここのコンマの意味がわかりません。タプルと関係ありますか?それとも過負荷の何かがありますか?

4

2 に答える 2

12

それは、同じ型の複数の変数を宣言しているだけです。

みたいな

int a, b;

最初の行は、PetscIntという型の 4 つの変数( に初期化されます)、配列、および最後にを宣言します。2 行目では、タイプ の 3 つの変数を宣言しています。in10col[3]itsPetscScalar

したがって、この:

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

以下と同じです:

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

元の方法の方が短く、入力が簡単で、変数が同じ型 (の一部) を共有していることを示しているため、優れていると考える人もいます。混乱したり、エラーが発生しやすいと感じる人もいますが、これはもちろん主観的なものですが、このようなコードを頻繁に見つける理由を動機付けるために言及する必要があると感じました.

于 2016-11-02T09:48:12.277 に答える
4

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.

于 2016-11-02T09:49:21.537 に答える