Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do condition expressions always evaluate to 0 or 1 in C?

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;
like image 656
pythonic Avatar asked Jul 23 '12 17:07

pythonic


People also ask

What is condition expression?

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.

What happens when an if statement conditional is not true?

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.

Which operators are used for compound conditions in 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.

Which of these logical expressions is always true?

A tautology is a logical expression that is always TRUE, regardless of the assignment of truth values to the variables in the expressions.


1 Answers

The logical operators (&&, ||, and !) all evaluate to either 1 or 0.

C99 §6.5.13/3:

The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

C99 §6.5.14/3:

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

C99 6.5.3.3/5:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

like image 134
James McNellis Avatar answered Sep 28 '22 19:09

James McNellis