Ternary Conditions

I've been doing some work with my menu class and I'm a big fan of using the ternary conditions. My question is, is it better to use a bunch of these, or better to use a bunch of if statements to create my variables?

Code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
      // Print Title
      VP_GoToXY(( /* X Value*/
                 (strHPosition == "right") ? (80 - strRightSelector.length() - strMenuTitle.length()) :
                 (strHPosition == "center") ? ((80 - strMenuTitle.length() - 2)/2) :
               /*(strHPosition == "left") ?*/ strLeftSelector.length()),
                ( /* Y Value */
                 (strVPosition == "bottom") ? (25 - Size() - 2) :
                 (strVPosition == "center") ? ((25 - Size() - 2)/2) :
               /*(strVPosition == "top") ?*/ 0));
      std::cout << strMenuTitle << std::endl;
      
      // Print Seperator
      VP_GoToXY(((strHPosition == "right") ? (80 - strRightSelector.length() - strMenuTitle.length()) :
                 (strHPosition == "center") ? ((80 - strMenuTitle.length() - 2)/2) : strLeftSelector.length()),
                ((strVPosition == "bottom") ? (25 - Size() - 2) :
                 (strVPosition == "center") ? ((25 - Size() - 2)/2) : 0) + 1);
      for(unsigned int i = 0; i < strMenuTitle.length(); i ++)
         std::cout << "-";


And by better, I mean which is easier on the cpu? Is there enough of a difference to be worried?
Last edited on
This code

1
2
3
4
5
6
      VP_GoToXY(((strHPosition == "right") ? (80 - strRightSelector.length() - strMenuTitle.length()) :
                 (strHPosition == "center") ? ((80 - strMenuTitle.length() - 2)/2) :
               /*(strHPosition == "left") ?*/ strLeftSelector.length()),
                ((strVPosition == "bottom") ? (25 - Size() - 2) :
                 (strVPosition == "center") ? ((25 - Size() - 2)/2) :
               /*(strVPosition == "top") ?*/ 0));


is difficult to read. And the reading of the code becomes even more difficult due to embedded comments. It is not clear for example how many arguments are specified.
It's a simple gotoxy(x,y) function. There is imbedded comments to show what the default value is for me personally. I was just wondering if putting two ternary conditions is better, since the variables could change a lot if I used them instead, or is it better to declare variables outside of the function?

Edit: Does that make it any clearer?
Last edited on
I already said that it is difficult to read your code.
Neither, switch case would be better. Especially if you #define LEFT, TOP, RIGHT, BOTTOM.
Then ignore the general code, it works perfectly.

All I'm asking is, is using ternary conditions in any way going to have a negative impact on running speed? Is it more beneficial to using variables that constantly have to be changed, or using ternary conditions and not using variables at all?
The speed difference (if that's what your asking) would likely be negligible. But as Vlad noted the code is nearly impossible to read.
Using ternary conditions never makes it "easy" to read. I have made it so that it works, and I have a ternary condition within another, which makes it even harder to read. I don't know how to exactly make it anymore readable.
I feel like a ternary would be the same as an if/else if chain.

Of course the speed difference is not noticeable. I don't think it's a good reason to code in a way that is slower though.

That said, I like to do as few computations as possible. Rule of thumb I have is if I need the function more than 4 times, store it as a variable.
Last edited on
Volatile Pulse wrote:
Using ternary conditions never makes it "easy" to read.
That's why they should be used sparingly. I dont feel any speed gained (if any) is worth making the code this unreadable.
Volatile Pulse wrote:
I don't know how to exactly make it anymore readable.
A couple if/else blocks? Ternary conditions are slick and look cool, but grouping them together (in a function call no less) like you are means anyone who reads the code has to stop and trace through to see exactly what you are doing. Unless you dont expect or want anyone to read your code favor readability unless the gain is worth it.

Edit: Besides I'm pretty sure this kind of optimization would be handled better by the compiler.
Last edited on
I guess I never really intended for others to read it, and since I understand it perfectly, well, then idk. If speed isn't going to be an issue, I think I'll stick to what I favor.

But at the same time, I do understand what you guys are saying about readability. And I love when people can read through my code and understand everything, however, I feel comfortable with the ternary conditions and like naraku9333 said, it seems cool to me.

Sorry for any confusion I created, I just don't like using if statements since a lot of lines, imho, get wasted that way, atleast with what I am doing.
Volatile Pulse wrote:
I just don't like using if statements since a lot of lines, imho, get wasted that way
I, personally dont pay per line so I tend to favor white space.
I know I'm kind of anal about these things, but I'm just going to go ahead.

First, I would enumerate the positions
enum position {LEFT = 0, TOP = 1, RIGHT = 2, BOTTOM = 3, CENTER = 4};

The function prototype, whatever it's name, can be set:
void setPosition(position pos1, position pos2);

Even in main(), you can call this function with:
setPosition(LEFT, TOP); // Whatever the name of the function is

Very easy to know where you want the position of the text.

Finally for the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// I would make variables instead of calculate a bunch of stuff
const unsigned int lenRight = strRightSelector.length() ;
const unsigned int lenLeft = strLeftSelector.length() ;
const unsigned int lenMenu = strMenutSelector.length() ;

// A variable to use with the switch
unsigned int arg1, arg2;

switch (pos1) 
{
case RIGHT  : arg1 = 80 - lenRight - lenMenu; break;
case CENTER : arg1 = (80 - lenMenu - 2) / 2; break;
case LEFT   : arg1 = lenLeft;
}
switch (pos2)
{
case BOTTOM : arg2 = 25 - Size() - 2; break;
case CENTER : arg2 = (25 - Size() - 2)/2; break;
case TOP    : arg2 = 0;
}
// Print title
VP_GoToXY(arg1, arg2);

// Menu Separater
if (strVPosition == CENTER) arg2++;
VP_GotToXY(arg1, arg2);

for (unsigned int i = 0; i < lenMenu; i++)
	std::cout << "-";
Last edited on
closed account (o3hC5Di1)
Hi there,

First off, thanks to LowestOne for that example - it's made me understand the practical use of enum better.

Second, I'd like to offer a kindly remark to Volatile Pulse.
You have all reason to be proud of your menu class, but please don't take it personally when people comment on your style of coding.
They are in fact trying to help you, and you did ask for opinions on the ternary operator.

You made reference to limiting the amount of lines in code in another topic too, this is a practice that was done way back when computer memory was tiny and numbers of lines did have an impact on performance. These days that does not hold as much and readability is much preferred over an extra line of code.

Personally I only use ternary operators as a shorthand for simple if/else variable assignments, nesting them or sequencing them easily becomes hard to read.

You also mention that you don't really intended to code to be read by someone else, which is fine, but remember that the practice you sow now is the habit you reap tomorrow. If you need to change your habits when you go to work on an open source projects, it will be much more tedious.

Anyway, I don't want to say one way or the other is "right", because quite frankly "to each his own" applies here. However, there are some guidelines which have been established by the experience of many programmers over the years and they have been so usually for a reason.

As I said - just a kindly remark, constructive criticism at the most :)

All the best,
NwN
I'd like to tell everyone, I do appreciate criticism. It helps me understand things that I thought were a good practice, just to find out it's not since it's harder to read. I fell in love with the ternary condition the moment I saw it. I thought this was one of the most awesome things ever. I do try to use it sparingly, but when I use them, they typically get nested, and become fairly large in size.

@LowestOne
I appreciate you taking the time to type all of that up for me to show me a different way of doing the same thing. Personally, I don't like switch statements, I'd prefer to use if/else blocks. Your example has given me insight on how to program without using the ternary conditions however. I also don't feel that it makes it more readable. I can see the assignments to each variable this way, but it isn't any easier for me to read than how I have my code laid out.

@naraku9333
I don't pay per line either, I prefer to keep my code a little shorter. Readability is a big thing to me, especially when I want to show off my code to someone, or have someone help me debug it. I always knew the ternary conditions weren't easily read and that's why I try to use them sparingly.

@NwN
I appreciate everyone's responses and I definitely didn't want to make this into a fight. Like you said, to each his own, and I have my own style, as most people here do. There is no right or wrong way, you're correct. To me, this is a lot easier to write and understand. Taking LowestOne's example actually feels like I'd be forcing myself to do something that doesn't feel natural to me.

Overall, I do want to say thank you to everyone that responded. Again, I do appreciate all of the criticism and I'll try to find better ways to write my unreadable code that I feel comfortable with. I like keeping code compact sometimes, other times I don't mind drawing it into several unnecessary lines just to be able to return to that line and see exactly what happened. If there might be an easier way to write my ternary conditions, I'd be up for that, otherwise I will keep searching for other ways to rewrite them using other methods.
I've had programs before that have seemed pretty slick before, but people look at it and say "Man I don't understand what you just did there". I blew it off as unimportant. Then sure enough, 6 months down the road when I had to look at the program, I had no idea what I was doing.

So, if someone can't read your code, chances are your future self can't either. Just my 2 cents.
I actually hate ternary operators because they are so slick. I will use them, but I will opt for an if/else block more often than not.

A couple of things you said:

All I'm asking is, is using ternary conditions in any way going to have a negative impact on running speed? Is it more beneficial to using variables that constantly have to be changed, or using ternary conditions and not using variables at all?


Taking LowestOne's example actually feels like I'd be forcing myself to do something that doesn't feel natural to me.


The switch statement will probably be slightly faster then the mish-mash of nested ternary operators you have in your code. With the switch, you only have the initial evaluation and a jump. You don't need to do multiple evaluations to get to the "else if" legs of the nested ternary operators.


I don't pay per line either, I prefer to keep my code a little shorter. Readability is a big thing to me, especially when I want to show off my code to someone, or have someone help me debug it. I always knew the ternary conditions weren't easily read and that's why I try to use them sparingly.


I like keeping code compact sometimes, other times I don't mind drawing it into several unnecessary lines just to be able to return to that line and see exactly what happened.


You state the importance of being able to let others review your code and help you debug. And you like to "show off" your code. We here are saying that condensing your code and using complex syntax like nested ternary operators hinders that. If somebody here at work wanted me to review code like yours, I would send it back telling them to add appropriate white space and use if/else statements or LowestOne's switch statements. The coding style you fell in love with would not last long here.

If you want us to say "cool use of ternary operators". OK. That was a really cool use of ternary operators. It certainly made 15 lines of understandable code fit into 5 lines of head scratcher. But there aren't many of us here who like it.
Topic archived. No new replies allowed.