-1

I'm trying to implement a decoder for a codec, and while reading the whitepaper I stumbled across this

Variable > 96000 ? 4 : 2; 

what does the question mark ? and the colon : between those two numbers do?

I've never seen this before (although I am a noob), and google isn't much help.

7
  • 8
    Search for "ternary operator in C" on Google. Commented Nov 28, 2014 at 4:47
  • 1
    If Variable is larger than 96000, the result is 4. Otherwise 2. Commented Nov 28, 2014 at 4:49
  • 3
    Was searching Google too much of a pain in the ass? Commented Nov 28, 2014 at 4:50
  • 2
    @CaptainObvlious: how would you find this in Google if you didn't know it was called "ternary operator"? Commented Nov 28, 2014 at 4:52
  • 2
    Possible duplicate of What does '?' do in C++? Commented Jan 18, 2020 at 21:03

5 Answers 5

2

This is ternary operator, this works like if else condition.

Variable > 96000 ? 4 : 2; 

In this line if Variable > 96000 is true it will return 4 else it will return 2

A traditional if-else construct in C

if (a > b) { result = x; } else { result = y; } 

This can be rewritten as the following statement:

result = a > b ? x : y; 
Sign up to request clarification or add additional context in comments.

Comments

1

?: is the conditional operator in C.

http://en.wikipedia.org/wiki/%3F%3A

http://www.eskimo.com/~scs/cclass/int/sx4eb.html

2 Comments

Link only answers are discouraged because if the link becomes old or invalid the response fails to help anyone.
It not a link only answer, it gives the name of the operator which should be enough for OP to google it.
0
return ( Variable > 96000 ) ? 4 : 2; 

translates to

if(Variable > 96000){ return 4; }else { return 2; } 

you are probably missing a return in the front of your statement.

1 Comment

not necessarily to miss a return, you can have int a = x>0 ? x: -x;
0

This is basically an equivalence statement in C , the following example will elaborate its use. In the example below, two numbers are compared and the larger number is returned.

#include <stdio.h> static int get_larger(int a, int b) { return (a > b) ? a : b; // if a is greater than b, return a, else return b } int main () { int a = 100; int b = 101; printf("Larger Number = %d\n", get_larger(a,b)); return 0; } 

Comments

0

Its ternary operator that is equivalent to If else condition in C/C++.

NOTE:

Its recommended to use parenthesis while using this operator to avoid side-effects of operator precedence problems as mentioned in Unexpected Result, Ternary Operator in Gnu C

Comments