交换期间堆栈溢出

发布于 2024-07-16 07:49:09 字数 71 浏览 7 评论 0原文

我们如何在不使用第三个变量的情况下处理两个变量交换期间发生的溢出。 我相信 XOR 解决方案只能用于整数。 其他变量类型呢?

How can we take care of the overflow happening during swapping of two variables without using a third variable. I believe the XOR solution can be used only for integers. what about other variable types?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

长梦不多时 2024-07-23 07:49:09

这不是答案,但不适合评论。

在什么情况下,您的运行距离如此接近可用堆栈存储的边缘,以至于额外使用临时变量进行交换会给您带来困难?

我可以看到一些嵌入式场景,但我很难想象一个场景,在这种情况下,堆栈空间如此紧张,这很重要(您不使用汇编语言编写代码)。

This isn't an answer but it doesn't fit in a comment.

Under what circumstances would you be running so close to the edge of your available stack storage that the additional use of a temporary variable for the swap is going to cause you difficulties?

I could see some embedded scenarios, but I'm hard pressed to imagine a scenario where you'd be so tight on stack space that this would matter (where you're not writing code in assembly language).

隔岸观火 2024-07-23 07:49:09

XOR 适用于任何您可以让 XOR 运算符处理的内容; 它是二进制数据的属性,而不是用于表示整数的二进制数据的属性。

XOR will work for anything you can get your XOR operator to process; it's a property of binary data, not of binary data used to represent integers.

断爱 2024-07-23 07:49:09

根本不做。 XOR 交换算法是一个很酷的技巧。 它不应在生产代码中使用

By not doing it at all. The XOR swap algorithm is cool hack. It shouldn't be used in production code.

独守阴晴ぅ圆缺 2024-07-23 07:49:09

XOR 解决方案适用于任何可以按位复制的类型,而不仅仅是整数。 但是,不要将变量与其自身进行异或:即

int x = 10;
int *p1 = &x;
int *p2 = p1;

*p1 = *p1 ^ *p2;
*p2 = *p1 ^ *p2;
*p1 = *p1 ^ *p2;

/* now x == 0 :( */

The XOR solution works with any type that can be bitwise copied, not just integers. However, do not XOR a variable with itself: i.e.

int x = 10;
int *p1 = &x;
int *p2 = p1;

*p1 = *p1 ^ *p2;
*p2 = *p1 ^ *p2;
*p1 = *p1 ^ *p2;

/* now x == 0 :( */
掌心的温暖 2024-07-23 07:49:09

XCHG? 不需要堆栈,没有溢出(进位标志)? 设置任一:)。

What's wrong with XCHG? No stack needed, no overflow(carry flag)? set either :).

若有似无的小暗淡 2024-07-23 07:49:09
a = a + b;
b = a - b;
a = a - b;

这适用于整数和浮点数。

a = a + b;
b = a - b;
a = a - b;

This will work for integers and float.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文