Logical Operators and Confusion of Equality (==) and Assignment (=) Operators in c programming

preview_player
Показать описание
Logical operators may be used to form complex conditions by combining simple conditions. The logical operators are && (logical AND), || (logical OR) and ! (logical NOT, or logical negation).

A condition containing the && (logical AND) operator is true if and only if both of the simple conditions are true.

C evaluates all expressions that include relational operators, equality operators, and/or logical operators to 0 or 1. Although C sets a true value to 1, it accepts any nonzero value as true.

A condition containing the || (logical OR) operator is true if either or both of the simple conditions are true.

The && operator has a higher precedence than ||. Both operators associate from left to right.

An expression containing && or || operators is evaluated only until truth or falsehood is known.

C provides ! (logical negation) to enable you to “reverse” the meaning of a condition. Unlike the binary operators && and ||, which combine two conditions, the unary logical negation operator has only a single condition as an operand.

The logical negation operator is placed before a condition when we’re interested in choosing a path of execution if the original condition (without the logical negation operator) is false.

In most cases, you can avoid using logical negation by expressing the condition differently with an appropriate relational operator.

Programmers often accidentally swap the operators == (equality) and = (assignment). What makes these swaps so damaging is that they do not ordinarily cause syntax errors. Rather, statements with these errors ordinarily compile correctly, allowing programs to run to completion while likely generating incorrect results through runtime logic errors.

You may be inclined to write conditions such as x == 7 with the variable name on the left and the constant on the right. By reversing these terms so that the constant is on the left and the variable name is on the right, as in 7 == x, then if you accidentally replace the == operator with =, you’ll be protected by the compiler.
The compiler will treat this as a syntax error, because only a variable name can be placed on the left-hand side of an assignment statement.

Variable names are said to be lvalues (for “left values”) because they can be used on the left side of an assignment operator.
Constants are said to be rvalues (for “right values”) because they can be used only on the right side of an assignment operator. lvalues can also be used as rvalues, but not vice versa.
Рекомендации по теме
welcome to shbcf.ru