Condition expression such as those involving && and ||, do they always evaluate to 0 or 1? Or for true condition, numbers other than 1 are possible? I am asking because I want to assign a variable like this.
int a = cond1 && cond2;
I was wondering if I should do the following instead.
int a = (cond1 && cond2)? 1:0;
A conditional expression has the general form. where expr1 is an expression that yields a true or false result. If the result is true, the value of the conditional expression is set to expr2. If the result is false, the value of the conditional expression is set to expr3.
If the conditional is not true then the line of code immediately after the else statement will be executed and then "flow of control" will pass to the next statement following the if-else statement.
Compound conditions may also be built using the && (and) and || (or) operators. When using multiple operators, always use parenthesis to indicate the desired order-of-precedence. Once an if statement is written, it becomes one statement unto itself.
A tautology is a logical expression that is always TRUE, regardless of the assignment of truth values to the variables in the expressions.
The logical operators (&&
, ||
, and !
) all evaluate to either 1
or 0
.
C99 §6.5.13/3:
The
&&
operator shall yield1
if both of its operands compare unequal to0
; otherwise, it yields0
. The result has typeint
.
C99 §6.5.14/3:
The
||
operator shall yield1
if either of its operands compare unequal to0
; otherwise, it yields0
. The result has typeint
.
C99 6.5.3.3/5:
The result of the logical negation operator
!
is0
if the value of its operand compares unequal to0
,1
if the value of its operand compares equal to0
. The result has typeint
. The expression !E is equivalent to (0==E).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With