LoginSignup
0
0

More than 5 years have passed since last update.

代入と三項演算子を組み合わせる時は、演算子の優先順位に注意

Posted at

↓のように書くと「"sss and bbb"」と出力されそうな気がするが

s = "sss and "

s << "aaa" == "aaa" ? "bbb" : "ccc"

p s

結果は↓

"sss and aaa"

と出てしまう。「<<」の演算子の優先順位が「==」より高いため、代入が先に動いしまうよう。

なので、()をつけて右辺の優先順位を上げてあげないとダメ。

s = "sss and "

s << ("aaa" == "aaa" ? "bbb" : "ccc")

p s

↓結果

"sss and bbb"

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0