swap関数
昨日に続きswap関数の実装例をいろんな言語でやってみる。
問題を再掲する。
「2つの引数を与えその値を入れ替える関数swapを書け。」
C#。仮引数で参照渡しを宣言したうえで呼び出し側も
参照渡しを明示しなければならない。
文法的に安全側に振ってある感じがするしC#ってC、Java、C++、VBをよく
研究して作ってあるなと感じる。
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void swap(ref int x, ref int y) { int tmp; tmp = x; x = y; y = tmp; } static void Main(string[] args) { int x, y; x = 3; y = 7; Console.WriteLine("before: x = " + x + ", y = " + y); swap(ref x, ref y); Console.WriteLine("after: x = " + x + ", y = " + y); } } }
お次はVB。
こうして眺めると一番、謎の呪文が少ないのはVBだ。
本来よけいな呪文を書かなくていいのはperlだと思っていたけど
strictに書こうとすると結構よけいな呪文が入ってくる。
VBは初心者向けに悪くない選択とはいえるかな。
Module Module1 Sub swap(ByRef x, ByRef y) Dim tmp As Integer tmp = x x = y y = tmp End Sub Sub Main() Dim x As Integer Dim y As Integer x = 3 y = 7 Console.WriteLine("before: x = " & x & ", y = " & y) swap(x, y) Console.WriteLine("after: x = " & x & ", y = " & y) End Sub End Module