Reputation:
Our professor gave us this code. It assigns a value to a char[] depending on the value of the first index in the array. He said it was an if statement but I've never seen one like this. I'm new to c++
temp.byte[0] = byte[0] == '0' ? '1' : '0';
Upvotes: 1
Views: 208
Reputation: 1
Using a fully parenthesized expression makes the meaning of the ternary operator more clear:
temp.byte[0] = ((byte[0] == '0') ? '1' : '0');
Upvotes: 0
Reputation: 695
This
temp.byte[0] = byte[0] == '0' ? '1' : '0';
can also be interpreted as
temp.byte[0] = (byte[0] == '0' ? '1' : '0'); //L-value is `temp.byte[0]`
In other words,
"Does byte[0] == '0'
?
If it does, then temp.byte[0] = '1'
Else, temp.byte[0] = '0'
.
Upvotes: 0
Reputation: 88
That's called a ternary operator, and they're kinda weird. They're a shorthand for an if-statement.
The format is:
condition ? if-true : if-false
In this case, the condition is is byte[0] == '0'
. If true, temp.byte[0]
is set to '1'
, otherwise temp.byte[0]
is set to '0'
.
Upvotes: 2
Reputation: 211590
Ternary operators are common to a lot of languages. It's roughly equivalent to an if
that returns either the first or second value. The first value is used in the true case, the second if false. A way to remember this is condition?
is a sort of question and the first thing after that is the answer.
There's a few guidelines for using them:
if
would be simpler.Upvotes: 4
Reputation: 2620
This line of code is equivalent to:
if byte[0] == '0'
temp.byte[0] = '1'
else
temp.byte[0] = '0';
This is a basic stuff in c++. Take a look for example at www.learncpp.com
Upvotes: 0