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;
}
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.
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.
The statement
is equivalent to
So it returns 1 if n is '1' and 0 otherwise.
the format is:
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.