Is It Okay to Use "And", "Or" etc. Instead of "&&", "||"

Is it okay to use and, or etc. instead of &&, ||?

They are in fact standard in C++, as defined by the ISO 14882:2003 C++ standard 2.5/2 (and, indeed, as defined by the 1998 edition of the standard). Note that they are built into the language itself and don't require that you include a header file of some sort.

However, they are very rarely used, and I have yet to see production code that actually uses the alternative tokens. The only reason why the alternative tokens exist in the first place is because these characters on some keyboards (especially non-QWERTY ones) were either nonexistent or clumsy to type. It's still in the standard for backwards compatibility.

Even though they are standard, I highly recommend that you don't use them. The alternative tokens require more characters to type, and the QWERTY keyboard layout already has all the characters needed to type out C++ code without having to use the alternative tokens. Also, they would most likely bewilder readers of your code.

2.5/2 Alternative tokens

In all respects of the language, each
alternative token behaves the same,
respectively, as its primary token,
except for its spelling. The set of
alternative tokens is defined in Table
2.

Table 2 - alternative tokens
+--------------+-----------+
| Alternative | Primary |
+--------------+-----------+
| <% | { |
| %> | } |
| <: | [ |
| :> | ] |
| %: | # |
| %:%: | ## |
| and | && |
| bitor | | |
| or | || |
| xor | ^ |
| compl | ~ |
| bitand | & |
| and_eq | &= |
| or_eq | |= |
| xor_eq | ^= |
| not | ! |
| not_eq | != |
+--------------+-----------+

Difference between && and and operators

What is the difference between the && and and operators?

There is none1. The "alternative" aspect of these operators means that they can be used to construct the exact same expressions from a semantic perspective.

Where and when do I use and over &&?

This is largely a matter of preference. I'm too used to && to not use it, but can understand if someone finds and more readable.

why does C++ introduce alternative operators?

C++ was designed to be available on a variety of character sets and platforms. Trigraphs, like Bathsheba pointed out, are another example of such a feature. If a character set would not allow && to be written (say, because it simply didn't have the & character) then one can still get by with the alternative representation. Nowadays, it's largely moot.



1 Actually, upon further thinking, my answer to your first question can be refined. There is a slight lack of equivalence, pertaining to how tokens are parsed. && doesn't require a space to be parsed as a separate token, while and does. That means:

void foo(bool b1, bool b2) {
if(b1&&b2) { // Well formed
}

if(b1andb2) { // ill formed, needs spaces around `and`
}
}

Usage of '&' versus '&&'

& is a bitwise AND, meaning that it works at the bit level. && is a logical AND, meaning that it works at the boolean (true/false) level. Logical AND uses short-circuiting (if the first part is false, there's no use checking the second part) to prevent running excess code, whereas bitwise AND needs to operate on every bit to determine the result.

You should use logical AND (&&) because that's what you want, whereas & could potentially do the wrong thing. However, you would need to run the second method separately if you wanted to evaluate its side effects:

var check = CheckSomething();
bool IsValid = isValid && check;

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

Difference between | and || , or & and &&

The operators |, &, and ~ act on individual bits in parallel. They can be used only on integer types. a | b does an independent OR operation of each bit of a with the corresponding bit of b to generate that bit of the result.

The operators ||, &&, and ! act on each entire operand as a single true/false value. Any data type can be used that implicitly converts to bool. Many data types, including float implicitly convert to bool with an implied !=0 operation.

|| and && also "short circuit". That means whenever the value of the result can be determined by just the first operand, the second is not evaluated. Example:

ptr && (*ptr==7) If ptr is zero, the result is false without any risk of seg faulting by dereferencing zero.

You could contrast that with (int)ptr & (*ptr). Ignoring the fact that this would be a bizarre operation to even want, if (int)ptr were zero, the entire result would be zero, so a human might think you don't need the second operand in that case. But the program will likely compute both anyway.

Why '&&' and not '&'?

In most cases, && and || are preferred over & and | because the former are short-circuited, meaning that the evaluation is canceled as soon as the result is clear.

Example:

if(CanExecute() && CanSave())
{
}

If CanExecute returns false, the complete expression will be false, regardless of the return value of CanSave. Because of this, CanSave is not executed.

This is very handy in the following circumstance:

string value;
if(dict.TryGetValue(key, out value) && value.Contains("test"))
{
// Do Something
}

TryGetValue returns false if the supplied key is not found in the dictionary. Because of the short-circuiting nature of &&, value.Contains("test") is only executed, when TryGetValue returns true and thus value is not null. If you would use the bitwise AND operator & instead, you would get a NullReferenceException if the key is not found in the dictionary, because the second part of the expression is executed in any case.

A similar but simpler example of this is the following code (as mentioned by TJHeuvel):

if(op != null && op.CanExecute())
{
// Do Something
}

CanExecute is only executed if op is not null. If op is null, the first part of the expression (op != null) evaluates to false and the evaluation of the rest (op.CanExecute()) is skipped.

Apart from this, technically, they are different, too:

&& and || can only be used on bool whereas & and | can be used on any integral type (bool, int, long, sbyte, ...), because they are bitwise operators. & is the bitwise AND operator and | is the bitwise OR operator.

To be very exact, in C#, those operators (&, | [and ^]) are called "Logical operators" (see the C# spec, chapter 7.11). There are several implementations of these operators:

  1. For integers (int, uint, long and ulong, chapter 7.11.1):

    They are implemented to compute the bitwise result of the operands and the operator, i.e. & is implement to compute the bitwise logical AND etc.
  2. For enumerations (chapter 7.11.2):

    They are implemented to perform the logical operation of the underlying type of the enumeration.
  3. For bools and nullable bools (chapter 7.11.3 and 7.11.4):

    The result is not computed using bitwise calculations. The result is basically looked up based on the values of the two operands, because the number of possibilities is so small.

    Because both values are used for the lookup, this implementation isn't short-circuiting.

If statement with && and multiple OR conditions in PHP

&& takes precedence over ||, thus you would have to use parentheses to get the expected result:

if (isset($_POST['cookieGiftBox']) && (!isset($POST['sugar']) || ...)

Actually, to get check if nothing is selected, you would do something like this:
if checkbox is checked and not (sugar is checked or chocolatechip is checked) or the equivalent:
if checkbox is checked and sugar is not entered and chocolatechip is not entered....
If you want to know more, search for information about Boolean algebra.

Update: In your example and in the correct syntax the sentence I took as an example would like this (for the first sentence, note the not (!) and the parentheses around the fields, not the checkbox):

if (isset($_POST['cookieGiftBox']) &&
!(
isset($_POST['sugar']) ||
isset($_POST['chocolatechip'])
)
) { error ...}

Or the second sentence, which might be easier to understand (note the && instead of ||):

if (isset($_POST['cookieGiftBox']) &&
!isset($_POST['sugar']) &&
!isset($_POST['chocolatechip'])
) { error...}

Using ands makes sure it is only true (and thus showing the error) if none of the sugar, chocolatechips, etc. fields are set when the giftbox checkbox is checked.
So if the checkbox is checked, and no fields are set it looks like this:
(true && !false && !false) which is equivalent to (true && true && true) which is true, so it shows the error.
If the checkbox is checked and sugar is entered it would look like this:
(true && !true && !false), equ. to (true && false && true), equ. to false and thus no error is shown.
If both sugar and chocolatechip are entered also no error will be shown.

C++ Double Address Operator? (&&)

This is C++11 code. In C++11, the && token can be used to mean an "rvalue reference".

Should I use two where clauses or && in my LINQ query?

I personally would always go with the && vs. two where clauses whenever it doesn't make the statement unintelligible.

In your case, it probably won't be noticeble at all, but having 2 where clauses definitely will have a performance impact if you have a large collection, and if you use all of the results from this query. For example, if you call .Count() on the results, or iterate through the entire list, the first where clause will run, creating a new IEnumerable<T> that will be completely enumerated again, with a second delegate.

Chaining the 2 clauses together causes the query to form a single delegate that gets run as the collection is enumerated. This results in one enumeration through the collection and one call to the delegate each time a result is returned.

If you split them, things change. As your first where clause enumerates through the original collection, the second where clause enumerates its results. This causes, potentially (worst case), 2 full enumerations through your collection and 2 delegates called per member, which could mean this statement (theoretically) could take 2x the runtime speed.

If you do decide to use 2 where clauses, placing the more restrictive clause first will help quite a bit, since the second where clause is only run on the elements that pass the first one.

Now, in your case, this won't matter. On a large collection, it could. As a general rule of thumb, I go for:

  1. Readability and maintainability

  2. Performance

In this case, I think both options are equally maintainable, so I'd go for the more performant option.



Related Topics



Leave a reply



Submit