-1

Possible Duplicate:
To ternary or not to ternary?

Today, while reading through my C book I stumbled upon a little gem: the ? operator. It is a ternary operator that acts like an if else statement based on weather or not a statement is true or false.

Apparently using the ? operator is supposed to be more efficient.

The following code uses an if / else statement (assuming somefunc returns NULL on failure):

foo = somefunc();
if(foo) printf("\nFunction Suceeded!");
else printf("\nFunction Failed!");

This is code is the same as the first but uses the ? operator:

somefunc() ? printf("\nFunction Suceeded!") : printf("\nFunction Failed!");

I can see how this will not be useful most of the time, however I know I've seen countless instances where this could have been easily used in place of an if / else statement.

Is it good practice to use this method?

Community
  • 1
  • 1
Keith Miller
  • 1,337
  • 1
  • 16
  • 32

2 Answers2

3

Efficiency aside, you should use whichever is more readable.

Efficiency included, if the ? were really more efficient, the compiler would definitely automatically rewrite any if statements to ? expressions. Why wouldn't it?

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
1

Use the ternary operator sparingly. It's definitely useful and can be an appropriate abbreviation, but it also can lead to less readable code. Your example demonstrates this.

pb2q
  • 58,613
  • 19
  • 146
  • 147