Can you please explain the code below? I am mostly confused about the "if" part. If there is no argument (eg. 5<8) in the if, how can it run/what does it do?
The if at line 11 does have "an argument". It could have been rewritten as if (W == 0).
Boolean values can be implied from any non-Boolean value not zero as true and 0 (zero) as false. !W simply inverts (NOT) the implied value.
Thank you for using code tags, but in the future it might be a good idea to include the header files in the code snippet. You should post a Short, Self Contained, Correct (Compilable), Example if'n at all possible.
That if ((In&1<<2) != 0) and (!W) = (W == 0) simplification really helped. Any similar ones that I might come across on exam?
Let me quickly comment on the code and please correct me where I might be wrong. Also, how do we get the last Out value?
The value of Out before the second if statement is 10.
Out &= ~(1 << 1)
moving 1 to the left gets us 0b10
~ and we get 0b01
1010 &= 01 ....is 0?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
uint8_t In = 5, Out = 8, W = 85;
if (In&1<<2) { //Because (In&1<<2) isn't 0, the values inside the if statements get changed.
W=In;
Out ^= 2;
}
In ^= W;
if (!W) { //If W would be 0 the if statement would be read, but because it isn't it jumps to "else".
W=Out;
Out |= 1<<1;
}
else
Out &= ~(1 << 1); //Why does this line change the value of Out from 10 to 8?
W ^= W;
If this is for an exam, the pedantically correct answer would be:
!W is interpreted as !bool(W)
ie. W (the operand of the built-in logical operator ! is contextually converted to bool,
and the bool result of that conversion is then negated.
Standard boolean conversions:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer-to-member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. https://eel.is/c++draft/conv.bool#1