Getting tslint warning on performing bit-wise and - tslint

I am performing bit-wise and operation and checking result with some other value using === in typescript code.
(res & 2) === 2

TSLint is a linter for TypeScript, meaning it's a separate library that checks for best practices in your code. In most (but not all) projects, bitwise operations like | or & are typos in code that was meant to be || or &&. See https://palantir.github.io/tslint/rules/no-bitwise.
If you do intend to do a |, disable the no-bitwise rule in your tslint.json: https://palantir.github.io/tslint/usage/configuration/

Related

When does C++11 give warnings about operator precedence?

When writing code, for a long time I knew that && has higher precedence than ||; however, compiling it using the C++11 standard gave me a warning that I should now use parentheses when using both in a single statement.
Now I got a warning that combining >> and + also should have parentheses. Now my statements look really ugly, with 5 or more parentheses floating around them.
1) Is there a resource that says which combinations of operators now require parentheses?
2) Is there a way to silence just the operator precedence warnings, but to keep the other warnings?
Compiler gcc with flags -O2 -Wall -g
The warnings came in when I added the flag -std=c++11
Sample expression:
(((string[0] << CHAR_BIT) + string[1] << CHAR_BIT) + string[2] << CHAR_BIT) + string[3];
When does C++11 give warnings about operator precedence?
The only case when the standard requires a diagnostic message (note that the standard does not distinguish between warnings and errors that halt the compilation) is when the program violates the standard. Except when the compiler is excempt from that with wording "no diagnostic required".
All other warnings are optional for the compiler and not required by the standard.
1) Is there a resource that says which combinations of operators now require parentheses?
No, because the parentheses are not required. The warning is just a suggestion by the compiler. The program is well-formed.
The warnings came in when I added the flag -std=c++11
For what it's worth, my GCC warns regardless of the standard argument.
2) Is there a way to silence just the operator precedence warnings, but to keep the other warnings?
The warning itself tells which warning option has enabled it (here is the warning from my GCC):
warning: suggest parentheses around '+' inside '<<' [-Wparentheses]
To disable, you can use the corresponding option to disable it: -Wno-WHATEVER.
Now my statements look really ugly, with 5 or more parentheses floating around them.
I recommend instead to extract the repetitive structure, and reuse a standard algorithm:
std::accumulate(string, string + 4, 0, [](auto sum, auto value) {
return (sum << CHAR_BIT) + value;
});
Much fewer parentheses :) Note that in C++11 (prior to C++14) you can not use auto as the type of an argument of a lambda. I don't know what types you use.
See the gcc manual:
-Wparentheses
Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected,
or when operators are nested whose precedence people often get
confused about.
Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that
of ordinary mathematical notation.
Also warn for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ?: operator is a
boolean expression, the omitted value is always 1. Often programmers
expect it to be a value computed inside the conditional expression
instead.
(I added the emphasis)
To turn this behavior off, specify -Wno-parentheses to gcc/g++.

Why don't programming languages use simplified boolean expressions?

I've never understood why we use syntax like this:
if (a == b || a == c)
when it could be simplified to something like this:
if (a == b || c)
Is this an issue with compilers or something? Can we really not account for a string of code like this and make it work?
There is no technical limitation that would make it impossible (or even too difficult) to implement a language that treats a == b || c as a shortcut for a == b || a == c. The problem is that it would be almost (?) impossible to come up with rules to do so only in the cases where that's what's expected.
For instance consider the expression result == null || fileIsClosed where fileIsClosed is a boolean. Surely the programmer would not expect this to be treated as result == null || result == fileIsClosed. You could come up with additional rules like "the replacement is only applied if the right operand of || is not a boolean", but then the replacement also does not work if you do booleanResult == possibleResult1 || possibleResult2. In fact the only thing about this example, that tells us whether the programmer intended for the replacement to happen, are the names of the variables. Obviously the compiler can't infer meaning from variable names, so it'd be impossible to do what the user wants in every case, making simple rules without exceptions (like "expr1 || expr2 is true iff at least one of expr1 and expr2 are true") preferable.
So in summary: We don't want the replacement to take place in all cases and inferring in which cases the replacements would make sense with complete accuracy would be impossible. Since it should be easy to reason about code, implementing a system that may or may not apply the replacement based on rules that 90% of programmers won't know or understand will lead to confusing behavior in certain cases and is therefore not a good idea.
Some part of the answer is: if (a == b || c) would not be interpretable without context or knowing the meaning behind this expression.
Consider the following situation:
What if c would be a boolean expression or a boolean value by itself? It could then be interpreted as either:
if (a has the value of b OR c is true)
if (a has the value of b OR c)
Now what was the intention when a human being coded these lines? ... *think. We don't exactly know nor does a compiler when it is asked to produce object code to be executed on a machine (as intended by the developer).
Or more drastically: A compiler can (and should) not guess, like humans sometimes do.
You can, you are just using the wrong programming language :)
In Icon for example, you can write a = (b | c). The way that works is that | really concatenates sequences, and = (equality) filters them (where false is no results, and true is some results). It implements this through back-tracking.
You can do even crazier things, like write ((0 to 4) > 1) * 3 will print out 6 9 12.
As you already know the string you wrote would have different meaning. However, some languages provide extension to change the behavior of the operator. You can use it if you want to define your own custom operations.

TCL how to require both operands to determine result in IF statement

new to TCL and running into a short circuit issue it seems. Coming from vbscript, I'm able to perform this properly, but trying to convert to a TCL script I'm having issues with the short circuit side effect and have been trying to find the proper way of doing this.
In the following snippet, I want to execute "do something" only if BOTH sides are true, but because of short circuiting, it will only evaluate the second argument if the first fails to determine the value of the expression.
if {$basehour != 23 && $hours != 0} {
do something
}
Maybe I'm not searching for the right things, but so far I've been unable to find the solution. Any tips would be appreciated.
The && operator always does short-circuiting in Tcl (as it does in C and Java and a number of other languages too). If you want the other version and can guarantee that both sub-expressions yield booleans (e.g., they come from equality tests such as you're doing) then you can use the & operator instead, which does bit-wise AND and will do what you want when working on bools. If you're doing this, it's wise to put parentheses around the sub-expressions for clarity; while everyone remember the precedence of == with respect to &&, the order w.r.t. & is often forgotten. (The parentheses are free in terms of execution cost.)
if {($basehour != 23) & ($hours != 0)} {
do something
}
However, it's usually not necessary to do this. If you're wanting an AND that you're feeding into a boolean test (e.g., the if command's expression) then there's no reason to not short-circuit, as in your original code; if the first clause gives false, the second one won't change what value the overall expression produces.

Why use short-circuit code?

Related Questions: Benefits of using short-circuit evaluation, Why would a language NOT use Short-circuit evaluation?, Can someone explain this line of code please? (Logic & Assignment operators)
There are questions about the benefits of a language using short-circuit code, but I'm wondering what are the benefits for a programmer? Is it just that it can make code a little more concise? Or are there performance reasons?
I'm not asking about situations where two entities need to be evaluated anyway, for example:
if($user->auth() AND $model->valid()){
$model->save();
}
To me the reasoning there is clear - since both need to be true, you can skip the more costly model validation if the user can't save the data.
This also has a (to me) obvious purpose:
if(is_string($userid) AND strlen($userid) > 10){
//do something
};
Because it wouldn't be wise to call strlen() with a non-string value.
What I'm wondering about is the use of short-circuit code when it doesn't effect any other statements. For example, from the Zend Application default index page:
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
This could have been:
if(!defined('APPLICATION_PATH')){
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
}
Or even as a single statement:
if(!defined('APPLICATION_PATH'))
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
So why use the short-circuit code? Just for the 'coolness' factor of using logic operators in place of control structures? To consolidate nested if statements? Because it's faster?
For programmers, the benefit of a less verbose syntax over another more verbose syntax can be:
less to type, therefore higher coding efficiency
less to read, therefore better maintainability.
Now I'm only talking about when the less verbose syntax is not tricky or clever in any way, just the same recognized way of doing, but in fewer characters.
It's often when you see specific constructs in one language that you wish the language you use could have, but didn't even necessarily realize it before. Some examples off the top of my head:
anonymous inner classes in Java instead of passing a pointer to a function (way more lines of code).
in Ruby, the ||= operator, to evaluate an expression and assign to it if it evaluates to false or is null. Sure, you can achieve the same thing by 3 lines of code, but why?
and many more...
Use it to confuse people!
I don't know PHP and I've never seen short-circuiting used outside an if or while condition in the C family of languages, but in Perl it's very idiomatic to say:
open my $filehandle, '<', 'filename' or die "Couldn't open file: $!";
One advantage of having it all in one statement is the variable declaration. Otherwise you'd have to say:
my $filehandle;
unless (open $filehandle, '<', 'filename') {
die "Couldn't open file: $!";
}
Hard to claim the second one is cleaner in that case. And it'd be wordier still in a language that doesn't have unless
I think your example is for the coolness factor. There's no reason to write code like that.
EDIT: I have no problem with doing it for idiomatic reasons. If everyone else who uses a language uses short-circuit evaluation to make statement-like entities that everyone understands, then you should too. However, my experience is that code of that sort is rarely written in C-family languages; proper form is just to use the "if" statement as normal, which separates the conditional (which presumably has no side effects) from the function call that the conditional controls (which presumably has many side effects).
Short circuit operators can be useful in two important circumstances which haven't yet been mentioned:
Case 1. Suppose you had a pointer which may or may not be NULL and you wanted to check that it wasn't NULL, and that the thing it pointed to wasn't 0. However, you must not dereference the pointer if it's NULL. Without short-circuit operators, you would have to do this:
if (a != NULL) {
if (*a != 0) {
⋮
}
}
However, short-circuit operators allow you to write this more compactly:
if (a != NULL && *a != 0) {
⋮
}
in the certain knowledge that *a will not be evaluated if a is NULL.
Case 2. If you want to set a variable to a non-false value returned from one of a series of functions, you can simply do:
my $file = $user_filename ||
find_file_in_user_path() ||
find_file_in_system_path() ||
$default_filename;
This sets the value of $file to $user_filename if it's present, or the result of find_file_in_user_path(), if it's true, or … so on. This is seen perhaps more often in Perl than C, but I have seen it in C.
There are other uses, including the rather contrived examples which you cite above. But they are a useful tool, and one which I have missed when programming in less complex languages.
Related to what Dan said, I'd think it all depends on the conventions of each programming language. I can't see any difference, so do whatever is idiomatic in each programming language. One thing that could make a difference that comes to mind is if you had to do a series of checks, in that case the short-circuiting style would be much clearer than the alternative if style.
What if you had a expensive to call (performance wise) function that returned a boolean on the right hand side that you only wanted called if another condition was true (or false)? In this case Short circuiting saves you many CPU cycles. It does make the code more concise because of fewer nested if statements. So, for all the reasons you listed at the end of your question.
The truth is actually performance. Short circuiting is used in compilers to eliminate dead code saving on file size and execution speed. At run-time short-circuiting does not execute the remaining clause in the logical expression if their outcome does not affect the answer, speeding up the evaluation of the formula. I am struggling to remember an example. e.g
a AND b AND c
There are two terms in this formula evaluated left to right.
if a AND b evaluates to FALSE then the next expression AND c can either be FALSE AND TRUE or FALSE AND FALSE. Both evaluate to FALSE no matter what the value of c is. Therefore the compiler does not include AND c in the compiled format hence short-circuiting the code.
To answer the question there are special cases when the compiler cannot determine whether the logical expression has a constant output and hence would not short-circuit the code.
Think of it this way, if you have a statement like
if( A AND B )
chances are if A returns FALSE you'll only ever want to evaluate B in rare special cases. For this reason NOT using short ciruit evaluation is confusing.
Short circuit evaluation also makes your code more readable by preventing another bracketed indentation and brackets have a tendency to add up.

Is there any wisdom behind "and", "or" operators in Ruby?

I wonder why ruby give and, or less precedence than &&, || , and assign operator? Is there any reason?
My guess is that's a direct carry-over from Perl. The operators or and and were added later in Perl 5 for specific situations were lower precedence was desired.
For example, in Perl, here we wish that || had lower precedence, so that we could write:
try to perform big long hairy complicated action || die ;
and be sure that the || was not going to gobble up part of the action. Perl 5 introduced or, a new version of || that has low precedence, for exactly this purpose.
An example in Ruby where you could use or but not ||:
value = possibly_false or raise "foo"
If you used ||, it would be a syntax error.
The difference is precedence. ||, && have higher precedence than =, but and, or have lower. So while you can do:
a = nil || 0
You would have to do:
a = (nil or 0)
to get same effect. If you do:
a = nil or 0
The result of expression would still be 0, but a value would be nil.
They have very low precedence so that the operands don't have to be wrapped in parentheses, as is sometimes the case with && and ||.
Being able to control the precedence of your operators is sometimes useful, especially if you are concerned with readability -- extra parenthesis in conditional statements can sometimes obscure the actual logic.
To be frank, though, I think the reason Ruby has the boolean operator precedence levels it does stems mostly from the fact that Matz was a Perl programmer before he ever wrote Ruby, and borrowed much of the core syntax and operators from that language.
I believe the idea is specifically to get them below the assignment operators, so you can write logic tests with assignments but without parens.

Resources