2

Possible Duplicate:
The ternary (conditional) operator in C

This is a code example from my teacher assistance. I don't have a clue what total = total*2+ (n=='1'? 1:0); does. I think it multiply the total with by 2, but what is with the question mark and the 1:0 ratio ?

int bcvt(FILE *infile){
  char n;
  int i, total=0;
  for(i=0; i<32; i++){    
    fscanf(infile, "%c", &n);
    total = total*2+ (n=='1'? 1:0);
  }
  char dummy;
  fscanf(infile, "%c", &dummy);
  return total;
}
Community
  • 1
  • 1
Learning C
  • 679
  • 10
  • 27
  • I wouldn't even know where to start search or the keyword to search for. Thanks sixlettervariables – Learning C May 15 '12 at 00:02
  • no problem. Every new person to C/C++ gets tripped up by what to call it. – user7116 May 15 '12 at 00:05
  • @CarlNorum, Give him a break, Searching for the ternary operator is difficult since you need to know it is called the ternary operator first... I had the exact same problem many years ago, I ended up finding it by searching for "question mark operator". – verdesmarald May 15 '12 at 00:06
  • That's my point - googling "question mark c" turns up [this link](http://crasseux.com/books/ctutorial/The-question-mark-operator.html) as the first hit. – Carl Norum May 15 '12 at 00:09
  • @CarlNorum, unless it ninja autocompletes your sentence into "question mark clipart". – chris May 15 '12 at 07:39
  • 2
    Where do people get the idea that they can learn C without ever opening an introductory C book? – Jim Balter May 15 '12 at 08:05

4 Answers4

3

The statement

(n=='1'? 1:0)

is equivalent to

if ( n == '1' ) return 1
else return 0

So it returns 1 if n is '1' and 0 otherwise.

the format is:

( expression ? if-true-return-this-value : else-return-this-value )
stefanB
  • 77,323
  • 27
  • 116
  • 141
1

It's similar to an if statement. Depending on whether the condition

n=='1'

is true or false, the operation will return the left side of (1:0) for true and the right side for false.

The values could be anything. 1 and 0 are random here.

if (n == '1') {
   return 1;
}
else {
   return 0;
}
hermann
  • 6,237
  • 11
  • 46
  • 66
0

The conditional operator here does this: "if n is equal to 1, then use 1, else use 0". So it will add 1 or 0 to the first expression based on n's value.

It's another way to write an if/else statement.

CDubbz31
  • 141
  • 3
  • 10
0

this expression "(n=='1'? 1:0)" is equivalent to if ( n == '1') return 1; else return 0; As stated, it is the ternary (conditional) operator in C.

And I'm guessing your code is loading then converting a binary string "0001010" to an integer.

Samy Arous
  • 6,794
  • 13
  • 20