What does this do? [duplicate]

2020-02-14 07:27发布

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;
}

标签: c binary
4条回答
够拽才男人
2楼-- · 2020-02-14 07:56

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.

查看更多
别忘想泡老子
3楼-- · 2020-02-14 08:09

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;
}
查看更多
Anthone
4楼-- · 2020-02-14 08:10

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 )
查看更多
来,给爷笑一个
5楼-- · 2020-02-14 08:19

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.

查看更多
登录 后发表回答