Java |
class Test {
static void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
public static void main(String[] args) {
int x = 1;
int y = 2;
System.out.println("pre: x = " + x + " y = " + y);
swap(x, y);
System.out.println("post: x = " + x + " y = " + y);
}
}
The output of the program is:
pre: x = 1, y = 2
post: x = 1, y = 2
NOTE: You have to use reference type to make swap work
in such situation.
|
|
C# |
class Test {
static void Swap(ref int a, ref int b) {
int t = a;
a = b;
b = t;
}
static void Main() {
int x = 1;
int y = 2;
Console.WriteLine("pre: x = {0}, y = {1}", x, y);
Swap(ref x, ref y);
Console.WriteLine("post: x = {0}, y = {1}", x, y);
}
}
The output of the program is:
pre: x = 1, y = 2
post: x = 2, y = 1
|
|