Express a truth table using a single if-condition - c++

My code looks like this:
/*
* A B
* 0 0 -> 1
* 0 1 -> 0
* 1 0 -> 0
* 1 1 -> 0
*/
#define A condition_1
#define B condition_2
if (A) {
// do nothing
} else {
if (B) {
// do nothing
} else {
// do something
}
}
Above I've reported the truth table for two conditions where 1 is true and 0 is false, is there a way to express the truth table into a single if-condition?

Your truth table represents a NOR (not or) operation. You can get that easily by combining logical NOT (!) with logical OR (||)
if (!(A || B)) {
}
PS. Please, don't use #define macros. It's very error-prone and tends to bite programmers who use it. Most often there are safer and more readable ways to perform what macro does.

Use:
if (!A && !B) {
// do something
}
Think, your truth table only returns 1 when both conditions are false (0 0 -> 1).
You can use ! in both to invert it.

If there is only one 1 in the table then it's essentially AND operation. If there is only one 0 then it's OR operation. If there are two of both then you can make it an equality operation.
When you know which operation to chose your next step is to figure out which operands should be negated. For AND both operands must turn to 1 to produce 1 (1 AND 1 = 1), so negate those who would otherwise produce 0. For OR it's opposite, negate those who would produce 1 when trying to have 0 a s result (0 OR 0 = 0)
For equality operation bear in mind that bool can either be true or false, so there are only two values. If you try to use something that is not a bool for a logical operand then there would be problems. With that in mind when you want to produce equality negate any of the operands if originally they don't produce correct result (0 == 0 = 1 and also 1 == 1 = 1, if you understand me).
In your particular case we have only one 1 in the table so it's an AND operation. Both operands are 0 for this 1 outcome so we have to negate both of them:
!A && !B

Related

Purpose of double inversion in a statement next to each other [duplicate]

This question already has answers here:
!! c operator, is a two NOT?
(4 answers)
Closed 10 years ago.
I have encountered the following snippet:
pt->aa[!!(ts->flags & MASK)] = -val;
What does !! (double exclamation marks/ exclamation points/ two NOT operators) stand for in c?
Doesn't (!!NULL) == NULL?
! is negation. So !! is negation of negation. What is important is the fact that the result will be an int.
!!x if x == 0 is !!0, that is !1, that is 0.
!!x if x != 0 is !!(!0), that is !!1, that is !0, that is 1.
!! is used commonly if you want to convert any non-zero value to 1 while being certain that 0 remains a 0.
And indeed, !!NULL == NULL, since !!NULL == !!0 and !!0 == !1 and finally !1 == 0.
Consequently, in the short piece of code you cited the array subscript will be either 0 if the value of the expression in parenthesis is NULL, and 1 otherwise.
It is commonly (ab)used to convert any value into the ints 0 or 1 by repeated application of the boolean not operator, !.
For instance: !56 is 0, since 56 is "true" when viewed as a boolean. This means that !!56 is 1, since !0 is 1.
!E is the same as E == 0 so !!E is the same as (E == 0) == 0. !! is used to normalize booleans values.
In C99 you can replace it by
#include <stdbool.h>
pt->aa[(bool)(ts->flags & MASK)] = -val;
Of course if your code is to be portable to C89 then you'd be better off doing the !! trick or
pt->aa[(ts->flags & MASK)!=0] = -val;
or
pt->aa[(ts->flags & MASK)?1:0] = -val;
The generated code will be certainly identical.
It converts a number into a canonical Boolean.
And note that in this case it's critical to do so, since the result is being used to index an array.
!!x is just a !(!x).
if NULL is defined as 0 then !!NULL == !!0 == !(!0) == !(1) == 0.
!! is a decent way to quiet the compiler in certain situations such as assignment in a conditional with more than one expressions, e.g:
int _blah = 100;
int *blah;
if ( _blah > 100 && !!(blah = &_blah) ) {
// do stuff
}
I don't recommend this -- warnings are usually there to enforce good coding practice.

Lua if A != (X or Y or Z)?

So I have this function that takes in an integer. But It doesn't work and I suspect that the if statement is not valid, I could not find anything on google regarding the issue, maybe my googling skills just suck.
if mynumber != (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) then
print("Please choose an integer number between 1-8")
end
Thanks for any help!!
Correct. That is not how you test things like that. You cannot test multiple values that way.
or requires expressions on either side and evaluates to a single expression. So (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) evaluates to 0 and your final expression is just if mynumber != 0 then.
To test multiple values like that you need to use or around multiple comparison expressions.
if (mynumber ~= 0) or (mynumber ~= 1) or (mynumber ~= 2) ... then (also notice ~= is the not-equal operator not !=).
Also be sure to note YuHao's answer about the logic in this line and how to test for this correctly.
Others have pointed the major problems you have, i.e, 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 evaluates as 0, the rest is ignored because of short-circuit. You need to test the number with these numbers one by one.
However, there's one last trap. The condition
if mynumber ~= 0 or mynumber ~= 1 then
is always true, because a number is either not equal to 0, in which case mynumber ~= 0 is true; or it is equal to 0, in which case mynumber ~= 1 is true.
The correct logic should be:
if mynumber ~= 0 and mynumber ~= 1 then
Etan's answer explains the behaviour as observed in lua. I'd suggest writing a custom FindIn function for searching:
function FindIn( tInput, Value )
for _ in pairs( tInput ) do
if Value == tInput[_] then return true end
end
return false
end
if FindIn( {1,2,3,4,5,6,7,8}, mynumber ) then
-- ...
end
try this:
In Lua You check if two items are NOT EQUAL by "~=" instead of "!=",
If You compare two items in if statement, then always remember that items should return booleans, so: instead of mynumber != (0 or 1 or...) try something like (mynumber ~= 0) or (mynumber ~= 1) ...
You can do it simple with .... (mynumber have to be integer variable)
if mynumber<0 or mynumber>8 then
print("Please choose an integer number between 1-8")
end

Complex if condition

In a legacy code, I have encountered the following expression:
if (!m_bMsOcs && bChannelData || m_bMsOcs && !bStunType)
I guess the intended condition was
if ((!m_bMsOcs && bChannelData) || (m_bMsOcs && !bStunType))
I am not sure. How is the original conditional expression supposed to execute? Please help.
The precedence of logical operators is:
! > && > ||
so your guess is correct.
if ( ((!m_bMsOcs) && bChannelData) || (m_bMsOcs && (!bStunType)) )
The operator precedence is ! > && > ||
This is an operator precedence question. The parenthesis take precedence, followed by your logicals. As && has greater priority than ||, you're correct in your guess.
Logical and have higher precedence than or: link
So you are right about the logic.
Your own answer is correct:)
If (this and that) or (this and that)
So if either of the ands are correct it evaluates true
As others have said, the two expressions are equivalent because of C++ precedence rules.
Here's a truth table that might help make it clear what will happen (I agree that the conditional expression is more complex than I like, too):
m_bMsOcs bChannelData bStunType Execute?
======== ============ ========= ========
0 0 0
0 0 1
0 1 0 Y
0 1 1 Y
1 0 0 Y
1 0 1
1 1 0 Y
1 1 1
Note that the 1 and 0 in the table just represent true/false values (i.e., the variables don't have to have a value of 1 - any non-zero value will be treated as a 1). I just find the table to be more readable using 0/1 instead of T/F.

In C++ syntax, can the condition of the if else, return a int and still execute the statements within

Here is the code which compiles :
int select_object = 0;
if( select_object ) //condition returns an int
{
printf("Hello");
}
if condition returns an int and not a boolean will the hello be printed ? When I tested this it printed hello.
Any idea why even for an int it executes the print statement.
THanks
In C and C++, any nonzero integer or pointer is considered true. So, since select_object is 0, it should not be printing Hello.
Boolean logic
1 = True
0 = False
1 && 0 = False 0
1 && 1 = True 1
1 || 1 = True 1
1 || 0 = True 1
So the answer is for non-zero it is considered true, for 0 it is considered false. If your value (your int) returns 0 it won't execute. If it returns a value that is not 0 it will execute.
In C or C++, a bool is just a fancy way of saying 'int with special values'. Every logical test (if, while, for, etc) can use an int or a pointer for its test instead of a bool, and anything that isn't 0 is true. NULLs and 0 are equal in this sense.

evaluate whether a number is integer power of 4

The following function is claimed to evaluate whether a number is integer power of 4. I do not quite understand how it works?
bool fn(unsigned int x)
{
if ( x == 0 ) return false;
if ( x & (x - 1) ) return false;
return x & 0x55555555;
}
The first condition rules out 0, which is obviously not a power of 4 but would incorrectly pass the following two tests. (EDIT: No, it wouldn't, as pointed out. The first test is redundant.)
The next one is a nice trick: It returns true if and only if the number is a power of 2. A power of two is characterized by having only one bit set. A number with one bit set minus one results in a number with all bits previous to that bit being set (i.e. 0x1000 minus one is 0x0111). AND those two numbers, and you get 0. In any other case (i.e. not power of 2), there will be at least one bit that overlaps.
So at this point, we know it's a power of 2.
x & 0x55555555 returns non-zero (=true) if any even bit it set (bit 0, bit 2, bit 4, bit 6, etc). That means it's power of 4. (i.e. 2 doesn't pass, but 4 passes, 8 doesn't pass, 16 passes, etc).
Every power of 4 must be in the form of 1 followed by an even number of zeros (binary representation): 100...00:
100 = 4
10000 = 16
1000000 = 64
The 1st test ("if") is obvious.
When subtracting 1 from a number of the form XY100...00 you get XY011...11. So, the 2nd test checks whether there is more than one "1" bit in the number (XY in this example).
The last test checks whether this single "1" is in the correct position, i.e, bit #2,4,6 etc. If it is not, the masking (&) will return a nonzero result.
Below solution works for 2,4,16 power of checking.
public static boolean isPowerOf(int a, int b)
{
while(b!=0 && (a^b)!=0)
{
b = b << 1;
}
return (b!=0)?true:false;
}
isPowerOf(4,2) > true
isPowerOf(8,2) > true
isPowerOf(8,3) > false
isPowerOf(16,4) > true
var isPowerOfFour = function (n) {
let x = Math.log(n) / Math.log(4)
if (Number.isInteger(x)) {
return true;
}
else {
return false
}
};
isPowerOfFour(4) ->true
isPowerOfFour(1) ->true
isPowerOfFour(5) ->false