Friday, May 19, 2006

Question mark: The ternary operator ?

You want to write short blocks of code and you want to write readable code. Usually, there's a fine line, as you don't want your code looking like the works of a l33t h4X0r script kid or a python minimalist.

A fine way of both shortening and simplifying is if you use the question mark. It's called a ternary operator. With this, you can do conditional assignments on one line.

Consider the following example (taken from Bresenhams line algorithm) :



int ystep;
if(y0<y1)
{
ystep = 1;
}
else
{
ystep = -1;
}



The code above could be shortened to one line:


int ystep = y0 < y1 ? 1 : -1;


5 comments:

Mr Monkey said...

Nice. This also works in Java[Script], and possibly other stuff too.

Once I forgot the exact syntax and name of this technique - you try searching for it without those! ;)

Anonymous said...

the ternary operator is available in almost every programming language.

Anonymous said...

Of course, the 'original' (if-then-else) code is much more readable and understandable. And during debug, it's a lot easier to 'step through' the original code and see what's happening.

In release (full optimization) mode, both code snippets probably compile to the same assembly statements. So I suspect the ternary operator is merely a 'vesigal remain' from the days of less-optimal compilers.

Anonymous said...

While the ternary operator may be harder to read, using it can considerably shorten a large script which in the end makes it easier to troubleshoot IMO :)

@ MrMonkey: "if statement shorthand" will usually turn up some results in google whenever I forget :)

Paul Williams said...

I found this page by searching 'C question mark operator'