English 中文(简体)
简言之:C#中为什么不寻常的行为因c/c++不同而有所不同 [复制]
原标题:Unary: Why unary s behavior in c# varies with c/c++ [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Undefined, unspecified and implementation-defined behavior
Undefined Behavior and Sequence Points
Pre & post increment operator behavior in C, C++, Java, & C#

我有这个法典:

int x = 2;
int y = x + 4 * ++x;
// what is y???

当我用<><><><><><>>>/strong>汇编和测试时。 页: 1

// C/C++
y is 15

但是,通过<><>c#。 页: 1

// C#
y is 14

www.un.org/Depts/DGACM/index_spanish.htm WHY?


IL:

locals init ([0] int32 x,
[1] int32 y)
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.4
IL_0005: ldloc.0
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: dup
IL_0009: stloc.0
IL_000a: mul
IL_000b: add
IL_000c: stloc.1
IL_000d: ldloca.s y
问题回答
int y = x + 4 * ++x;

在C和C++中,每个歌剧的评标次序没有说明,这意味着<条码>x或<条码>4*++x<>。 由于对歌剧的评价次序没有说明,整个表述的结果没有说明。

If x is evaluated before 4*++x, then y will be computed as:

int y = x + 4 * ++x; //original

int y = 2 + 4 * ++x  //evaluate x first
      = 2 + (4 * 3)  //evaluate 4 *++x then
      = 14;

同样,如果在<代码>x之前对<代码>4*++x进行评价,则对<代码>x进行评价。

int y = x + 4 * ++x; //original

int y = x + (4*3)  //evaluate 4 * ++x first
      = 3 + 12   //evaluate x then  (x is incremented)
      = 15;

在C#中,需要对歌剧进行评价,使之正确,因此,你们总是首先得到14项行为。

Actually, in C++ you just get undefined behavior, since the evaluation order of expressions is not always specified, so it s unclear whether the first use of x reads the old or new value. Both are possible, and in fact anything at all is possible because the standard explicitly says that it is undefined what happens.

C#作为安全语言,不能允许这种情况,因此更严格地界定评价顺序。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签