Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ternary operator

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys, I'm having some problems understandin why this code doesn't compile (from the OCA 8 study book)
What is theresult of the following code snippet?


A: Tiger
B: Lion
C: Tiger is Bigger
D: Lion is Bigger
E: is Bigger
F: doesn't compile because of line 5


I didn't quite understand the explanation which says that it's effectively a metter of operator precedence. Here is my own partial interpretation of the code:
As 250 < 338 only the first part of the expression doesn't execute, leaving us with final (it's the value of tiger that we're trying to copy into the variable statement ). So basically we're trying to assign is Bigger to another literal? is that it?
thanks
 
Henry Wong
author
Marshal
Pie
Posts: 22113
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:
I didn't quite understand the explanation which says that it's effectively a metter of operator precedence.

Well, basically, it is.... meaning after the compiler applies the precedence (and also, associatively), since the ternary operator has higher precedence than the assignment (and also, assignment has right to left assoc), this expression...

is basically the same as ...

and of course, this statement is invalid because the second assignment has a value on the left hand side (instead of a variable).

So...
Jason Attin wrote: leaving us with final (it's the value of tiger that we're trying to copy into the variable statement ). So basically we're trying to assign is Bigger to another literal? is that it?

Yes. Assigning a value to another value is not allowed. And your analogy worked...

Henry
 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cool, thanks!
 
Mala Gupta
Author
Ranch Hand
Posts: 363
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jason -

Here's how you can use () to modify and compile the code:



With much respect,
Mala
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic