未定义的行为,或者:Swift是否具有序列点? [英] Undefined behavior, or: Does Swift have sequence points?

查看:115
本文介绍了未定义的行为,或者:Swift是否具有序列点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中,第二个语句

In C/C++, the second statement in

int i = 0;
int j = i++ + i++ + ++i;

同时调用

  • 未指定行为,因为操作数的评估顺序 未指定,并且
  • 未定义的行为,因为相同对象i上的副作用相对于彼此没有顺序.
  • unspecified behavior, because the order of evaluation of operands is unspecified, and
  • undefined behavior, because the side effects on the same object i are unsequenced relative to each other.

例如参见

  • Why are these constructs (using ++) undefined behavior?
  • Undefined behavior and sequence points

现在,鉴于Swift被设计为 safe 语言,那么什么是 这里对应情况?是

Now, given that Swift was designed as a safe language, what is the corresponding situation here? Is the result of

var i = 0
let j = i++ + i++ + ++i

定义明确?可以从语言参考中得出结论吗? 斯威夫特那本书j == 4?

well-defined? Can one conclude from the language reference in the Swift book that j == 4?

推荐答案

Apple开发人员和Swift设计师Chris回答了这个问题 Apple开发者论坛中的Lattner https://forums.developer.apple.com/thread/20001 #63783 :

The question was answered by Apple developer and Swift designer Chris Lattner in the Apple Developer Forum https://forums.developer.apple.com/thread/20001#63783:

是的,该表达式的结果将始终为4. 从左到右的表达式,它不是未定义的或实现的 定义的行为,例如C.

Yes, the result of that expression will always be 4. Swift evaluates expressions left to right, it isn't undefined or implementation defined behavior like C.

克里斯还添加了:

也就是说,如果您编写这样的代码,就会有人试图对其进行维护 对你可能不会很满意

That said, if you write code like that, someone trying to maintain it will probably not be very happy with you

同意!这是说明问题的极端例子.

Agreed! It was meant as an extreme example to demonstrate the problem.

这篇关于未定义的行为,或者:Swift是否具有序列点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆