• 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
Sheriff
Posts: 22635
111
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: 368
12
  • 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
 
Gravity is a harsh mistress. But this tiny ad is pretty easy to deal with:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!