質問

Are the two ways of declaring variables shown below the same?

int aa= 0, bb= 0, cc= 0, dd= 0;

int aa= 0;
int bb= 0;
int cc= 0;
int dd= 0;
役に立ちましたか?

解決 2

YES

C# supports single statement can assign multiple local variables

A single statement can assign multiple local variables. Languages derived from C-style syntax often allow you to use commas to declare multiple variables in one statement. The C# language allows this.

From 8.5.1 Local variable declarations

A local variable declaration that declares multiple variables is equivalent to multiple declarations of single variables with the same type. Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.

First ones IL code;

 .locals init ([0] int32 aa,
           [1] int32 bb,
           [2] int32 cc,
           [3] int32 dd)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldc.i4.0
  IL_0004:  stloc.1
  IL_0005:  ldc.i4.0
  IL_0006:  stloc.2
  IL_0007:  ldc.i4.0
  IL_0008:  stloc.3
  IL_0009:  ret

Second one IL code;

  .maxstack  1
  .locals init ([0] int32 aa,
           [1] int32 bb,
           [2] int32 cc,
           [3] int32 dd)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldc.i4.0
  IL_0004:  stloc.1
  IL_0005:  ldc.i4.0
  IL_0006:  stloc.2
  IL_0007:  ldc.i4.0
  IL_0008:  stloc.3
  IL_0009:  ret

他のヒント

Yes, this:

int aa = 0, bb = 0, cc, dd;

is exactly the same as the following, more common and readable version:

int aa = 0;
int bb = 0;
int cc;
int dd;

And as Soner Gönül shows, they produce the same IL code.

But you asked a good question, because things can be more subtle than that.

Pointers

In unsafe C# you can work with pointers. A pointer to an integer is written as int*. So when you want to declare three variables of type int*, you might write this:

int* aa, bb, cc;

And that correctly represents your intentions:

int* aa;
int* bb;
int* cc;

However, the syntax for pointers came from the much older language C, and if you declare three pointer variables in C like this:

int* aa, bb, cc;

Then that means something subtly different, and you've actually written:

int* aa;
int bb;
int cc;

And that's why C developers will write int *aa instead, to show that only aa is a pointer type, and the rest are normal integers.

int *aa, bb, cc;

However, I discourage you from writing such a thing in C altogether: it is confusing.

Visual Basic and VB.Net

In Visual Basic.NET you can also declare variables on one line:

Dim aa, bb As Integer

And this is the same as:

Dim aa As Integer
Dim bb As Integer

But if you program in Visual Basic (VB.Net's predecessor), then this:

Dim aa, bb As Integer

Means:

Dim aa As Any     'aa Is Variant
Dim bb As Integer

They are the same. I would argue the second option is probably easier to read once your names get a bit more descriptive.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top