Tip of the week #1
Tags: operators, ternary, tips, tips of the week
Today is the first “Tip of the week”. A new mini series I’ll be publishing every week! So let’s get started.
Today’s subject is over Ternary operations. These operations can improve your code and make it easier to read. However sometimes can make your code really complex. A Ternary operation is basically just a if else statement that many languages support.
The general syntax usually looks similar to this.
(expression ? true expression : false expression)
So let’s start of with an example in C/C++.
#include <iostream>
int main()
{
int i = 0;
while(i != 5)
{
std::cout << i << ((i > 2) ? " > 2" : " <= 2") << std::endl;
i++;
}
}
Let’s break this down! If you never seen this, don’t freak out! It’s actually really simple.
((i > 2) ? " > 2" : " <= 2")
If the expression is true (i > 2) then it will return ” > 2″, if it’s false it will return ” A more simple of way of putting it would be the long form of code of that example.
#include <iostream>
int main()
{
while(i != 5)
{
std::cout << i;
if(i > 2)
{
std::cout << " > 2" << std::endl;
}
else
{
std::cout << " <= 2" << std::endl;
}
i++;
}
}
Now, I don’t know about you but I would rather write that using the ternary operator as its less lines and more compact. If you are interested in using this operation in another language just google it to see if your language supports it. Many languages support. The example above you can use in C, C++, C#, Objective-C, Actionscript, Javascript, Java, PHP. In those languages I must note you do not need the open bracket around the expression. I used them to make the code look cleaner and easier to read. Happy programming!