为什么在命令式或OO语言(例如C/C ++/C#/Java)中不存在交换/交换运算符? [英] Why doesn't a swap / exchange operator exist in imperative or OO languages like C/C++/C#/Java...?

查看:104
本文介绍了为什么在命令式或OO语言(例如C/C ++/C#/Java)中不存在交换/交换运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么许多语言没有内置这样简单而基本的操作,例如交换两个变量的内容.

这是计算机科学课程中最基本的编程练习之一;它在许多算法(例如排序)中大量使用;时不时地需要它,并且必须使用一个临时变量或使用模板/泛型函数.

它甚至是许多处理器上的基本机器指令,因此带有临时变量的标准方案将得到优化.

已创建了许多不太明显的运算符,例如赋值运算符(例如+ =,可能是为了反映累积的机器指令而创建的,例如add ax,bx)或??. C#中的运算符.

那是什么原因?还是它确实存在,我一直都想念它?

解决方案

根据我的经验,除了已经提到的排序算法以及偶尔在低级硬件戳中,在实际应用中这并不是普遍需要的,因此我认为通用语言有点特殊.

如前所述,并非所有处理器都将其作为指令来支持(许多处理器不支持大于字的对象).因此,如果它得到了一些有用的附加语义的支持(例如,原子操作),则将很难在某些处理器上进行支持,并且如果它不具有附加语义,那么它就是(很少使用)合成糖.

之所以支持赋值运算符(+ =等),是因为它们在现实世界的程序中更为常见-因此它们提供的语法糖更有用,并且作为一种优化-记住C可以追溯到60年代末70年代初期,编译器的优化并不那么先进(而且计算机的能力也有所降低,因此无论如何您都不希望冗长的优化通过).

保罗

I was always wondering why such a simple and basic operation like swapping the contents of two variables is not built-in for many languages.

It is one of the most basic programming exercises in computer science classes; it is heavily used in many algorithms (e.g. sorting); every now and then one needs it and one must use a temporary variable or use a template/generic function.

It is even a basic machine instruction on many processors, so that the standard scheme with a temporary variable will get optimized.

Many less obvious operators have been created, like the assignment operators (e.g. +=, which was probably created for reflecting the cumulative machine instructions, e.g. add ax,bx), or the ?? operator in C#.

So, what is the reason? Or does it actually exist, and I always missed it?

解决方案

In my experience, it isn't that commonly needed in actual applications, apart from the already-mentioned sort algorithms and occasionally in low level hardware poking, so in my view it's a bit too special-purpose to have in a general-purpose language.

As has also been mentioned, not all processors support it as an instruction (and many do not support it for objects bigger than a word). So if it were supported with some useful additional semantics (e.g. being an atomic operation) it would be difficult to support on some processors, and if it didn't have the additional semantics then it's just (seldom used) synatatic sugar.

The assigment operators (+= etc) were supported because these are much more common in real-world programs - and so the syntacic sugar they provide was more useful, and also as an optimisation - remember C dates from the late 60s/early 70s, and compiler optimisation wasn't as advanced (and the machines less capable, so you didn't want lengthy optimisation passes anyway).

Paul

这篇关于为什么在命令式或OO语言(例如C/C ++/C#/Java)中不存在交换/交换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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