What advantages are there to using either AND or &&? - language-features

Currently, I'm using && and || instead of AND and OR because that's how I was taught. In most languages, however, both are valid syntax. Are there any advantages to one or the other in any language?
I did try to search for this question, but it's a bit hard. It doesn't interpret my input correctly.

You ask “Are there any advantages to one or the other in any language?” This is, of course, dependent on the programming language.
Languages that implement both and and && (and correspondingly or and ||) will do it one of two ways:
Both behave exactly the same way. In which case, there is no advantage provided by the language in using one over the other.
Each behaves differently. In which case, the advantage is that you can get different behaviour by using one or the other.
That all sounds a bit facetious, but it's really as specific as one can get without talking about a specific language. Your question explicitly wants to know about all languages, but it's a question that needs to be answered per language.

Perl has all four of {&& || and or} but they differ in their precedence. "and" and "or" have really low precedence so you can do things like "complex-function-call-here or die $!" and you won't accidentally have "or" slurp up something on its left side that you didn't want it to.

it depends on the language, but on PHP, I'd be careful about using && versus "and". The ones i often use are "&&" and "||"
http://us3.php.net/manual/en/language.operators.logical.php
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true

In some languages && will have a higher operator precedence than AND.

If both works fine, then I would say it's really personal preference, in most cases, they are compiled into same binary code like this : 11100010001000101001001010 [not real code, just an example].

&& = two keystrokes of the same key.
AND = three keystrokes of different keys.

I'm not sure what language you are using, but some languages differentiate between a normal boolean operator and a short-circuit operator. For example, the following are normal boolean operators in MATLAB:
C = or(A,B);
C = A | B; % Exactly the same as above
However, this is a short-circuit operator:
C = A || B;
The short-circuit syntax will evaluate the first argument and then, depending on the value, will potentially skip over evaluating the second argument. For example, if A is already true, B doesn't have to be evaluated for an OR operation, since the result is guaranteed to be true. This is helpful when B is replaced with a logical operation that involves some kind of expensive computation.
Here's a wikipedia link discussing short-circuit operators and their syntax for a few languages.

Unless there aren't any precedence issues, I'd say there are differences in readability. Consider the following:
if (&x == &y && &y == &z) {
// ..
}
#define AND &&
if (&x == &y AND &y == &z) {
// ..
}

Related

Any practical differences in between "==" vs "in" or "if in" when checking string index?

Are there any practical differences between examples below and is better use one than others?
s = 'this#mail.is'
for i in range(len(email)):
print('#' in email[i])
#vs
for i in range(len(email)):
print(email[i] == '#')
#or
if '#' in email:
There is no practical difference... for your example here...
In essence, (as explained here and here), with in, python calls the underlying __contains__ function.
Thus, in your example. It makes no difference.
On the other hand, one could create a module and define a differente behavior for the __contains__ function.
I guess this would be done more for of an academic purpose, but it could still be made.
in checks for substrings
"a" in "apple" > True
== checks if it is exactly the same
b=10;
if(b==10)

What is the “and” and “or” Operator in Kotlin?

I used an || operator within the Kotlin IDEA but was throwing an error. This confused me, one of the first queries when searching google was a closed stack overflow thread with a snarky "answer" comment which wasn't helpful.
The first query in google hit is some function "or" gibberish.
My code:
if(inputAmount >= 0 || inputAmount = -99)
I understand what is "wrong". there was some logic errors the second part of the "if" statement should have been inputAmount == -99. In my case, the code needed to further be adjusted because of the actual type that was being used.
if(inputAmount >= 0.0 || inputAmount.toInt() == -99)
This appears to be different then other languages in that other languages just simply allow you to have your "logic" error with the "inputAmount = -99". So the '||' operator is allowed and is similar to most other languages.
So first step if encounter this error is to make sure your logic is correct. (check)
infix functions > sense according to the documentation "or" and "and" are infix functions that don't use the short circuit, is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'?
when referring to the infix 'or' how do people refer to that in Kotlin?
in boolean logic takes statements. A=b is a statement that is always true
No, it isn't. In C, C++ and Java it's an expression, and its value is the value of b. If b is false, it's false, if b is 10, it's 10. And you really don't want to confuse "statements" in programming languages with "statements" in logic; they are entirely different things.
Separately, C and C++ (but not Java) allow || to work on all integral types, and not just booleans (because they didn't originally have booleans as a separate type).
when referring to the infix function 'or' how do Kotlin folk typically refer to that?
Bitwise or for integral types, and I've never actually seen anyone use non-short-circuiting or on booleans, but if I had to I'd call it... well, non-short-circuiting or.
is it technically wrong to call the "||" operator an "or" operator and should be called logical 'or'
Both || and or (on booleans) are "logical 'or'" and I don't see any problem with calling them simply 'or'. If you need to distinguish use short-circuiting vs non-short-circuiting. But again, I've never actually ran into a use of the non-short-circuiting version.

Perform an assignment and an operation using a ternary operator + && in Objective-C?

In the name of ternary bliss (and for a disdain of the verbose)... I am hoping, and am somewhat surprised that....
BOOL isItOpen = YES;
isItOpen = (isItOpen ? YES : NO); // yes, dumbie, it's open.
works fine… but that…
isItOpen = (isItOpen ? [it close] && NO : [it open] && YES);
results in Invalid operands to binary expression ('void' and 'int')
I can't seem to track down a simple yes or no as to whether one can conditionally chain operations with && (or ||), like one does in say, BASH or PHP. I tried various combinations of & and && arrangements, to no avail.. as I am a C idiot... but if this "way of doing it" is NOT possible, linguistically… is there another - that is as concise? (ie, no ifs involed?)
The C (and by extension, C++ and Objective-C1) operators form expressions; they're designed to evaluate to a value, rather than control program flow.
So whilst ?:, && and || all offer short-circuit evaluation of their arguments, you can't use them to conditionally call arbitrary functions;2 you should use traditional control-flow constructs (i.e. if) for that.
You could use the little-known comma operator to achieve this, but I strongly recommend that you don't, because it's highly unidiomatic, and difficult to read. e.g.:
isItOpen = condition ? (func1(), NO) : (func2(), YES);
Actually, I don't know Objective-C. For all know, it might be possible!
And by "arbitrary", I mean functions that return void, or a type that's not implicitly convertible to bool in the case of && and ||, or a non-matching type in the case of ?:.
The difference you are experiencing is due to Objective-C having:
(a) true procedures (void functions/methods) which return no value; and
(b) a stronger type system than PHP
In your example the primary problem is (a) - you are calling methods which return nothing, and nothing is not a boolean value.
In PHP functions always return something, a function defined as returning void is actually defined as returning a "useless" value. However PHP will convert just about anything to anything (and does so inconsistently, for added "fun"), so a "useless" value has a boolean value - though what that is probably depends on the phase of the moon ;-) This feature does mean that you can reliably chain a "void" function after one which returns a value - <expr convertible to boolean> && <"void" function> will work in PHP (but the resulting boolean value is arbitrary). The same thing will not work in Objective-C (do not try to fix it with the comma operator, there are hidden traps with that operator).
So provided you stick with functions/methods which return either a boolean, or a type implicitly or explicitly convertible to boolean (e.g. for pointer types nil is false, other values true; for integral types 0 is false, everything else true) you can "conditionally chain" operations. Whether you should do this is a different question...
P.S. If you want to be confusing, this is short:
(isItOpen = !isItOpen) ? [it open] : [it close];
which will make most folks do a double-take ;-)
Your code would work fine as long as the close and open methods you are executing on it return boolean values. Otherwise, no cigar.
If you want to use the ternary operator, you can do like this:
isItOpen ? ([it close], isItOpen = NO) : ([it open], isItOpen = YES);
Or:
isItOpen ? [it close] : [it open];
isItOpen = !isItOpen;
But this is not a good programming style and you should avoid it.
The following code is much more readable (at least by a C/C++/Objective-C programmer):
if (isItOpen)
[it close];
else
[it open];
isItOpen = !isItOpen;
In order of preference, I recommend you use the third version of the code, then the second, then the first.

What is your preferred boolean pair: 1/0 Yes/No True/False?

When dealing with MySQL, I typically use the BOOLEAN type, which is equivalent to TINYINT(1), or 1/0
In most languages I work with, true/false is preferred
When displaying forms, sometimes "Yes / No" makes more sense
enum Bool
{
True,
False,
FileNotFound
};
http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
In code: true/false.
In the UI: Yes/No or OK/Cancel
true and false makes a lot more sense to me, in code - partly through familiarity, I'm sure. I suspect I'd get used to yes and no pretty quickly. 1 and 0 really doesn't work for me though.
Consider the expression
age == 5
It's a test for truth-hood. Is the value of age 5? Yes, it's true. Both "yes" and "no" would be fine for me, but the idea that the answer to the question "Is the value of age 5?" is "1" seems pretty counter-intuitive to me. Just because that's the typical binary representation of truth-hood doesn't mean it's a useful one at a higher abstraction.
Which is easier to read?
while(true) {}
while(yes) {}
while(1) {}
I'll stick with true for most cases.
Here are rules I live by...
Rule #1
Use well defined constants in the programming languages that you use to communicate with the CPU, i.e., true/false in most modern cases for boolean values. If a database offers a boolean type or some such equivalent, of course it should be used.
Rule #2
Interact with users of your software by using their preferred language and idiom, i.e., Yes/No questions should offer Yes/No (or perhaps an alternative to No, such as Cancel).
Rule #3
Uncertainty should be expressed in terms of scope, i.e., "that depends", which will be followed up by the question "on what?". I know developers who answer the question by copying and pasting just about every dependency they may need into every code file of a project as a 'using' statement. That's just sloppy, and please bother to alphabetize or at least group namespaces together.
When a bool Just Isn't Enough
Incidentally, an interesting twist to this, available in C#, is Nullable;
The you can write
Nullable<bool> RespondToIritatingQuestion()
{
return new Nullable<bool>();
}
OR
bool? RespondToIritatingQuestionWithSytle()
{
return new bool?();
}
and the questioner would need to evaluate your response before even knowing what the answer, if there is one, might be...
bool? answer = RespondToIritatingQuestionWithStyle();
if (answer.HasValue)
Trace.WriteLine("The bloke responded with " + answer.Value.ToString());
else
Trace.WriteLine("The bloke responded with 'depends'.");
1 or 0 for SQL. SQL has a boolean type for a reason. Also, in very large databases, it can effect performance.
I use booleans for true/false fields in databases. Some people use ENUM('true', 'false'), but thats not my preference. For programming languages, I always use true/false, even if setting it to 0 or 1 will work. And if the form requires 'yes'/'no', I still use booleans to represent the values, but display them as strings that are more logical.

Not keyword vs = False when checking for false boolean condition

When I'm using an If statement and I want to check if a boolean is false should I use the "Not" keyword or just = false, like so
If (Not myboolean) then
vs
If (myboolean = False) then
Which is better practice and more readable?
Definitely, use "Not". And for the alternately, use "If (myboolean)" instead of "If (myboolean = true)"
The works best if you give the boolean a readable name:
if (node.HasChildren)
Since there's no functional difference between either style, this is one of those things that just comes down to personal preference.
If you're working on a codebase where a standard has already been set, then stick to that.
Use True and False to set variables, not to test them. This improves readability as described in the other answers, but it also improves portability, particularly when best practices aren't followed.
Some languages allow you to interchange bool and integer types. Consider the contrived example:
int differentInts(int i, int j)
{
return i-j; // Returns non-zero (true) if ints are different.
}
. . .
if (differentInts(4, 8) == TRUE)
printf("Four and Eight are different!\n");
else
printf("Four and Eight are equal!\n");
Horrible style, but I've seen worse sneak into production. On other people's watches, of course. :-)
Additionally to the consensus, when there is both a true case and a false case please use
if (condition)
// true case
else
// false case
rather than
if (not condition)
// false case
else
// true case
(But then I am never sure if python's x is not None is the true-case or the false case.)
Definitely use "Not", consider reading it aloud.
If you read aloud:
If X is false Then Do Y
Do Y
Versus
If Not X Then Do Y
I think you'll find the "Not" route is more natural. Especially if you pick good variable names or functions.
Code Complete has some good rules on variable names. http://cc2e.com/Page.aspx?hid=225 (login is probably required)
! condition
In C and pre-STL C++, "!condition" means condition evaluates to a false truth value, whereas "condition == FALSE" meant that the value of condition had to equal what the system designed as FALSE. Since different implementations defined it in different ways, it was deemed better practice to use !condition.
UPDATE: As pointed out in the comment -- FALSE is always 0, it's TRUE that can be dangerous.
Something else: Omit the parentheses, they’re redundant in VB and as such, constitute syntactic garbage.
Also, I'm slightly bothered by how many people argue by giving technical examples in other languages that simply do not apply in VB. In VB, the only reasons to use If Not x instead of If x = False is readability and logic. Not that you’d need other reasons.
Completely different reasons apply in C(++), true. Even more true due to the existence of frameworks that really handle this differently. But misleading in the context of VB!
It does not make any difference as long you are dealing with VB only, however if you happen to use C functions such as the Win32 API, definitely do not use "NOT" just "==False" when testing for false, but when testing for true do not use "==True" instead use "if(function())".
The reason for that is the difference between C and VB in how boolean is defined.
In C true == 1 while in VB true == -1 (therefore you should not compare the output of a C function to true, as you are trying to compare -1 to 1)
Not in Vb is a bitwise NOT (equal to C's ~ operator not the ! operator), and thus it negates each bit, and as a result negating 1 (true in C) will result in a non zero value which is true, NOT only works on VB true which is -1 (which in bit format is all one's according to the two's complement rule [111111111]) and negating all bits [0000000000] equals zero.
For a better understanding see my answer on Is there a VB.net equivalent for C#'s ! operator?
Made a difference with these lines in vb 2010/12
With the top line, Option Strict had to be turned off.
If InStr(strLine, "=") = False Then _
If Not CBool(InStr(strLine, "=")) Then
Thanks for answering the question for me. (I'm learning)