can ternary statements be nested?

  • Thread starter Thread starter Josh
  • Start date Start date
Any sample to do nested ternary. Interesting!

int a = 1;

int b = 2;

int c = 3;

int d = 4;

int e = 5;

int f = 5;

int g = 5;

int r;

r = (a<b) ? (c<d) ? e : f : g;



It returns 5
 
You can nest them, but it's not usually good for readability.

Console.WriteLine((i < 0) ? "negative" : ((i > 0) ? "positive" :
"zero"));

P.
 
You can nest them, but it's not usually good for readability.
True but Im trying to write a single expression to check for collison
between 3d objects its already a nightmare!!!
 
I wouldn't create such constructs at all - totally unreadable (even this is
only a sample).
 
Hi,

It's kind of how you can traverse a matrix using a single for in C :)
I still remember the first time I delivered a homework with that in the
univ. the teacher gave me a 2 ( suspense in Cuba's grades ) just for that :)

It's better using two lines of code, or at least separate them in more than
one line, and use parentesis.


Cheers,
 
Hi,

Then make it the most readable possible something like:

r = (a<b) ?
(c<d) ? e : f
: g;

With one condition per line, instead of all in the same line.

Cheers,
 
I would consider breaking the nested structure into seperate structures only
if that would process quicker. Speed is everything what I'm doing. Some
experiments are needed.


Miha Markic said:
I wouldn't create such constructs at all - totally unreadable (even this is
only a sample).

--
Miha Markic [MVP C#] - RightHand .NET consulting & development
miha at rthand com
www.rthand.com

Josh said:
int a = 1;

int b = 2;

int c = 3;

int d = 4;

int e = 5;

int f = 5;

int g = 5;

int r;

r = (a<b) ? (c<d) ? e : f : g;



It returns 5
 
Back
Top