Using the ?: operator as opposed to if…else…

Using the ?: operator as opposed to if…else…

Is there a problem with using the ?: operator instead of the if…else… construct? For example, see the following:

if(iNum1 > iNum2)    iNum3 = iNum1;else    iNum3 = iNum2;

The above requires 4 lines of code. Yes, it's readable, but it could be written with just one line of code, that in my opinion is just as readable, as in the following example?

iNum3 = (iNum1 > iNum2) ? iNum1 : iNum2;

In this instance, I would prefer to use the ?: operator. Is there a problem in doing this? I have heard the argument that it is difficult to spot, and that it can be mininterpreted. Also, because it produces identical executable code, it may be better to use just the if...else... construct. However, I disagree with these comments as the person who tried to get me to accept them was looking through code that uses the ?: operator and spotted the use of them instantly and knew exactly what they did. What do you think?

As s rule, every language construct has a legitmate use (the only exception is deprecated features, which are listed in the Standard). The ? operator is therefore legit when used properly. The problem with ? is that many programmers tend to overuse or even misue it, just to save a few keystrokes, thereby creatinng indecipherable programs.

Now to you code snippet. There are three criteria to test the use of ?. First, is the code correct? In both cases, i.e., the if-else sequence or the ? shorthand, the code is correct. Next is readability. Usually, a sequence of if-else seems a little more readable but this is not always the case. In your code, the if-else sequence is rather long and therefore it may not be immedaitely clear what your intention was. In the ? version, the entire expression consists of one line of code so it's somewhat more intuitive. The third criterion is efficiency, but it's irrelevant in this case because you can see that the compiler expands the ? expression into an if-else sequence.

Thus, the ? has an advanatge of being a little bit more readable (in this case, but not necessarily in other cases). However, it's obvious that you're simply trying to extract the maximum value of a pair of numbers and assign it to another number. A much more readable choice, which is at least as efficient, and also shorter is this:

iNum3 = max(iNum1 > iNum2);

In general, you can almost without exception replace each ? expressions by either a max or min expression.

See also  5 Tips for Choosing the Right Medical Software for Your Practice

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist