-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.
    – 0xF1
    Nov 28, 2014 at 4:47
  • 1
    If Variable is larger than 96000, the result is 4. Otherwise 2.
    – Old Panda
    Nov 28, 2014 at 4:49
  • 3
    Was searching Google too much of a pain in the ass? 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"?
    – Eduardo
    Nov 28, 2014 at 4:52
  • 2
    Possible duplicate of What does '?' do in C++?
    – GSerg
    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;
1

?: is the conditional operator in C.

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

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

2
  • Link only answers are discouraged because if the link becomes old or invalid the response fails to help anyone. Nov 28, 2014 at 4:52
  • 2
    It not a link only answer, it gives the name of the operator which should be enough for OP to google it.
    – ouah
    Nov 28, 2014 at 4:53
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
  • not necessarily to miss a return, you can have int a = x>0 ? x: -x;
    – vsoftco
    Nov 28, 2014 at 4:56
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;
}
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