是(--i ==我++)不确定的行为? [英] Is (--i == i++) an Undefined Behavior?
本文介绍了是(--i ==我++)不确定的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题是涉及到我以前的问题。我得到的答案是的这是一个未定义的行为。的
请谁能解释:
- 什么是未定义的行为?
- 我的代码,我怎么能知道有一个未定义的行为?
示例代码:
INT I = 5;
如果(--i ==我++)
Console.WriteLine(平等且i =+ I);
,否则
Console.WriteLine(不等于我=+ I);
//输出:平等,I = 6
解决方案
这在C未定义,但在C#中明确:
从C#(ECMA-334)规范运算符优先级和结合一节(§ 14.2.1):
- 除了赋值运算符和空合并运算符,所有的
二元运算是左
关联的,这意味着从左至右操作
被执行。
[实施例:X + Y + z被评价为(X + Y)+ Z。例如结束]
块引用>
所以
- 我
首先计算,改变I
4,评估为4。然后我++
正在评估,改变I
5,但评估为4。this question is related to my previous problem. The answer I got was "It is an Undefined behavior."
Please anyone explain:
- What is an undefined behavior?
- how can I know my code has an undefined behavior?
Example code:
int i = 5; if (--i == i++) Console.WriteLine("equal and i=" + i); else Console.WriteLine("not equal and i=" + i); //output: equal and i=6
解决方案It's undefined in C, but well-defined in C#:
From C# (ECMA-334) specification "Operator precedence and associativity" section (§14.2.1):
- Except for the assignment operators and the null coalescing operator, all binary operators are left- associative, meaning that operations are performed from left to right. [Example: x + y + z is evaluated as (x + y) + z. end example]
So
--i
is evaluated first, changingi
to 4 and evaluating to 4. Theni++
is evaluating, changingi
to 5, but evaluating to 4.这篇关于是(--i ==我++)不确定的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文