user3325783
user3325783

Reputation:

What does this if assignment/statement mean in C++

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

Answers (5)

Luis Armendariz
Luis Armendariz

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

Don Larynx
Don Larynx

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

David E. Smith
David E. Smith

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

tadman
tadman

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:

  • Don't use a ternary when an equivalent if would be simpler.
  • Don't nest them.
  • Don't use a ternary unless you're assigning the result to something.
  • Try to avoid using them in function arguments.
  • Don't use negative conditions, instead flip the order of the last two parts.

Upvotes: 4

Igor Popov
Igor Popov

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

Related Questions