フォーラム


ゲスト  

ようこそ ゲスト さん。このフォーラムに投稿するには 登録が必要です。

ページ: [1]
トピック: Delphi と 三項演算子 (条件演算子)
DEKO
管理者
投稿数: 2690
Delphi と 三項演算子 (条件演算子)
on: 2013/04/06 10:36 Sat

Delphi に 三項演算子 はありませんが、VisualBasic の IIF() に相当する 関数 は存在します (Delphi 6 以降)。

// [StrUtils 名前空間]
function IfThen(AValue: Boolean; const ATrue: string; AFalse: string = ''): string;

// [Math 名前空間]
function IfThen(AValue: Boolean; const ATrue: Integer; const AFalse: Integer): Integer;
function IfThen(AValue: Boolean; const ATrue: Int64; const AFalse: Int64): Int64;
function IfThen(AValue: Boolean; const ATrue: Single; const AFalse: Single): Single;
function IfThen(AValue: Boolean; const ATrue: Double; const AFalse: Double): Double;
function IfThen(AValue: Boolean; const ATrue: Extended; const AFalse: Extended): Extended;

 
StrUtils / Math 名前空間に存在するので見つけにくいのかもしれませんね。
Math.IfThen() には気付いても、StrUtils.IfThen() には気付かなかったり…。

Indy の IdGlobal にも iif() があります。

// IdGlobal
function iif(ATest: Boolean; const ATrue: Boolean; const AFalse: Boolean): Boolean; overload;
function iif(ATest: Boolean; const ATrue: string; const AFalse: string = ''): string; overload;
function iif(ATest: Boolean; const ATrue: Integer; const AFalse: Integer): Integer; overload;
function iif(const AEncoding, ADefEncoding: TIdTextEncoding; ADefEncodingType: IdAnsiEncodingType = encASCII): TIdTextEncoding; overload;
DEKO
管理者
投稿数: 2690
Re: Delphi と 三項演算子 (条件演算子)
on: 2013/06/14 19:14 Fri

Delphi で三項演算子 (モドキ) があまり使われないのには理由があります。

  • 読みにくい
  • 他にもっといいやり方がある

例えば、値を返すだけの用途 (モドキと同じ用途) であれば、

var
Flg: Boolean;
const
BooleanString: array [Boolean] of string = ('False だよ', 'True だよ');
begin
Flg := True;
ShowMessage(BooleanString[Flg]);
end;

 
このようなコードが書けます。配列は順序値であれば何でもいいので、列挙型とかも指定できます。

var
Flg: TAlignment;
const
AlignmentString: array [TAlignment] of string = ('左寄せ', '右寄せ', '中央寄せ');
begin
Flg := taCenter;
ShowMessage(AlignmentString[Flg]);
end;

 
こんな感じで。配列は n 次元でも構わないので、以下のような書き方もできます。

const
ConditionNumber: array [Boolean, Boolean, Boolean] of SmallInt =
(((1, 2),(1, 3)),((1, 0),(0, 1)));

 
うまく使えば複雑に入り組んだ if 文をスッキリとした case 文に置き換える事ができます。

case ConditionNumber[(条件1), (条件2), (条件3)] of
0: ...;
1: ...;
2: ...;
3: ...;
end;

 
Boolean が 3 つなのですから、2^3 で 8 パターンを処理できます。コードを解りやすくするとこのようになります。

const
ConditionNumber: array [Boolean, Boolean, Boolean] of SmallInt =
(
(
( 1, // False, False, False の時に返される値
2 // False, False, True の時に返される値
),
(
1, // False, True, False の時に返される値
3 // False, True, True の時に返される値
)
),
(
(
1, // True, False, False の時に返される値
0 // True, False, True の時に返される値
),
(
0, // True, True, False の時に返される値
1 // True, True, True の時に返される値
)
)
);
begin
case ConditionNumber[(条件1), (条件2), (条件3)] of
0: ...;
1: ...;
2: ...;
3: ...;
end;
end;

 
つまり、この条件の時とこの条件の時は同じ処理 という場合に、"長い条件式を or で連結しなくてもいい" という事です。重複した条件式を書く必要もありません。

if 文が複雑になって同じコードを何箇所にも書くハメになった事がありませんか?

ページ: [1]
WP Forum Server by ForumPress | LucidCrew
バージョン: 1.7.5 ; ページロード: 0.037 sec.