# 如何在一行中交换两个变量？

## 本文概述

Python：在Python中, 有一个简单且语法简洁的结构来交换变量, 我们只需要编写” x, y = y, x”。

C/C++：以下是一种普遍提供的经典解决方案

``````//Swap using bitwise XOR (Wrong Solution in C/C++)
x ^= y ^= x ^= y;``````

``````//Swap using bitwise XOR (Correct Solution in C/C++)
//sequence point introduced using comma.
(x ^= y), (y ^= x), (x ^= y);``````

Java：在Java中, 明确定义了子表达式求值的规则。左操作数总是先于右操作数求值(请参见这个更多细节)。在Java中, 表达式” x ^ = y ^ = x ^ = y;”根据Java规则无法产生正确的结果。它使x =0。但是, 我们可以使用” x = x ^ y ^(y = x);”请注意, 表达式是从左到右计算的。如果最初x = 5且y = 10, 则该表达式等效于” x = 5 ^ 10 ^(y = 5);”。请注意, 我们无法像在C/C++中那样在C/C++中使用此函数, 也没有定义是否为任何运算符执行左操作数还是右操作数(请参见这个更多细节)

## C/C++

``````//C/C++ program to swap two variables in single line
#include <stdio.h>
int main()
{
int x = 5, y = 10;
(x ^= y), (y ^= x), (x ^= y);
printf ( "After Swapping values of x and y are %d %d" , x, y);
return 0;
}``````

## Java

``````//Java program to swap two variables in a single line
class GFG
{
public static void main (String[] args)
{
int x = 5 , y = 10 ;
x = x ^ y ^ (y = x);
System.out.println( "After Swapping values of x and y are "
+ x + " " + y);
}
}``````

## Python3

``````# Python program to swap two variables in a single line
x = 5
y = 10
x, y = y, x
print ( "After Swapping values of x and y are" , x, y)``````

## C#

``````//C# program to swap two
//variables in single line
using System;

class GFG
{
static public void Main ()
{
int x = 5, y = 10;
x = x ^ y ^ (y = x);
Console.WriteLine( "After Swapping values " +
"of x and y are " +
x + " " + y);
}
}

//This code is contributed by aj_36``````

## PHP

``````<?php
//PHP program to swap two
//variables in single line

//Driver Code
\$x = 5;
\$y = 10;
( \$x ^= \$y );
( \$y ^= \$x );
( \$x ^= \$y );
echo "After Swapping values of x and y are "
, \$x , " " , \$y ;

//This code is contributed by Vishal Tripathi
?>``````

``After Swapping values of x and y are 10 5``

• C ++还提供了库函数swap()
• b =(a + b)–(a = b)； [为此感谢Rajat Mishra]
• a + = b –(b = a)； [感谢Zoran Davidovi？为了这]
• a = a * b /(b = a)[为此感谢kongasricharan]

• 回顶