トップページが寂しくなってきたのでとりあえず投下
さて、どうやりましょ。ビギナなら
void func(int cond)
{
int n;
if ( cond )
n = 0;
else
n = 1;
}
なんてのもありですかね。しかしこの程度なら3項演算子を使って
void func(int cond)
{
int n = cond ? 0 : 1;
}
の方がスマートですね。しかし条件が複雑になってくると3項演算子では読みにくくなるので、前者の方がよいかもです。
んで、本題は複雑な条件で分岐した結果の値を直接初期値にする方法。C/C++で妥当なのは関数分けて
int init_n(void)
{
if ( complex_condition ) {
if ( more_complex_condition )
return 0;
else
return 1;
}
else if ( another_condition ) {
return 2;
}
/* else */
return 3;
}
void f()
{
int n = init_n();
}
な感じかな?rubyとかだとif文も式になるので、
n = if complex_condition then
if more_complex_condition then
0
else
1
end
elsif another_condition
2
else
3
end
とか、perlでもdoを使って、
my $n = do { if ( $complex_condition ) {
if ( $more_complex_condition ) {
0
}
else {
1
}
}
elsif ( $another_condition ) {
2
}
else {
3
}};
みたいにできます。
しかし世の中には「このように書ける」ではなく、「このようにして書かなければならない」言語も存在したりします。
<xsl:variable name="n" as="xs:integer" >
<xsl:choose>
<xsl:when test="$complex_condition" >
<xsl:choose>
<xsl:when test="$more_complex_condition" >
<xsl:value-of select="0" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="1" />
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:when test="$another_condition" >
<xsl:value-of select="2" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="3" />
<xsl:otherwise>
</xsl:choose>
</xsl:variable>
いやはやいやはや





コメントする