how will the precedence of && and != work in a logical statement? - pointers

While (ptr ! =NULL && dptr! = NULL && dptr->next! =NULL)
In this code if the pointer dptr is NULL will it work or will terminate?

If the statement is true or not is actually based not only on dptr but also on ptr and dptr->next. If the statement is true - the content if the while-loop will be executed.
The substatements (your camparisons to not NULL) are checked one after another - if one is false, the other will not be executed. This is true for most programming languages. Though I haven't checked with all.
Logical && as well as || have some inherent mechanism for fast return. They both go step by step from left to right substatement. (Plus () ). With && the check is aborted on the first false statement. With || the check is aborted on the first true statement. The other checks won't be reached.
So your statement will never check dptr->next != NULL for the case that dptr is actually NULL. So your statement is safe from access to NULL pointers.

Related

Writing an if statement when the value can be NULL or a string

I have a value that can be NULL or a string. The second test fails because a is of length 0.
How do I write an if-statement that handles both cases?
Example:
a <- NULL
if (is.null(a) | a=="something else then null") {
print("test")
}
is.null(a) || a=="something else then null"
(similarly, use && instead of & in a situation like this)
Explanation: when you use |, all conditions are checked one by one and then the "or" assertion is applied. This means that if one of the conditions is invalid, then there is an error, like in your case.
When you use ||, the "or" assertion is checked after each condition check. In your case, is.null(a) is TRUE. This means that is.null(a) "or" any other condition will also be TRUE, so there's no need to check the other condition.
This is based on my understanding of how it works, it's not a definition coming from the docs. I hope it's clearer.
More info: What's the differences between & and &&, | and || in R?

Why does this R function not short-circuit properly?

I'm working my way through the Data Science courses at DataCamp. (Not a plug.) One of the practice lessons has the following completed solution:
# logs is available in your workspace
extract_info <- function(x, property = "success", include_all = TRUE) {
info <- c()
for (log in x) {
if (include_all || !log$success) {
info <- c(info, log[[property]])
}
}
return(info)
}
# Call extract_info() on logs, no additional arguments
extract_info(logs)
# Call extract_info() on logs, set include_all to FALSE
extract_info(logs, include_all = FALSE)
The first call (extract_info(logs)) works as I would expect it to: it returns a vector containing all the log entries (regardless of the value of log$success).
The second call (extract_info(logs, include_all = FALSE)) does not return the results I would expect. It returns a vector containing only those results where log$success evaluates to FALSE.
It seems to me that the use of the || operator should cause the if block to short-circuit, and the second call should return nothing. From what I can tell, R evaluates expressions from left to right; but this looks like it's evaluating from right to left.
Can someone explain what's going on here?
(According to the site, this is the correct solution, and there's nothing wrong with the code. I want to know why it works the way it does. Even if the answer is that I'm overlooking something painfully obvious and stupid.)
Well || is the "or" operator. You don't short circuit the "or" operator with a FALSE value; you basically ignore that parameter and just look at the next one because you are looking for any TRUE value.
Assume a is a boolean value. These should be equivalent (<==>).
# or
FALSE || a <==> a
TRUE || a <==> TRUE
# and
TRUE && a <==> a
FALSE && a <==> FALSE
It seems like this was a temporary confusion.
|| is OR and so if either condition evaluates to TRUE, the compound expression evaluates to TRUE. If include_all was TRUE, you could short-circuit the expression, but when include_all is FALSE, you must wait to see what the other part is.

Collection deny rule property undefined

When invoking this in the browser console:
Meteor.users.update({_id:'2MA7iPq7bNtfxGm6r'},{$unset:{'profile.taskInProgress':''}})
This Meteor server code is giving this error
TypeError: Cannot read property 'profile.taskInProgress' of undefined
Meteor.users.deny({
update: function (userId, doc, fields, modifier) {
const tasks = ['search', 'aSearch'];
return (!(
userId &&
userId == Meteor.userId() &&
(tasks.indexOf(modifier.$set['profile.taskInProgress']) >= 0) || //<--comment for next line to work
(modifier.$unset['profile.taskInProgress'] == '') // <-- or comment for the above line to work
));
}
});
it works if I comment out the "error line", but if I do that then I will loose the permission to $set it. So now it appears like I can have one or the other but not both permissions. Must be some problem with my code.
How to allow the client to unset the 'profile.taskInProgress' property?
i think you have a logic problem.
your expression is basically this:
!(a && b && c || d)
c is valid only when you're doing a $set, and d is valid only when you're doing an $unset.
if your expression were this (without the prefixing bang):
(a && b && c || d)
... then, for a $set, the evaluation will be: a, b, c. if those are all true, then the condition is satisfied. it does not need to proceed to evaluation of d. that's good, because i think that would fail due to lack of null check.
but if $unset is used, then i believe that c will fail, because of a lack of null check. (i'm not positive here, but i think that's what's going on).
but, you have the entire expression "notted". that's going to force evaulation of each of a, b, c, and d, regardless of whether $set or $unset is being used. and this will always fail due to lack of null checks.
what you really mean, i think, is:
!(a && b && (c || d))
as written, you could not have a userId, and as long as d is true (and null checks were in place), you would allow the operation.
to solve it, i would break out the evaulation from the overall logic. e.g.
let userIdExists = !!userId;
let requesterIsLoggedInUser = (userId === Meteor.userId());
let progressSet = (modifier.$set && (tasks.indexOf(modifier.$set['profile.taskInProgress']) >= 0));
let progressUnset = (modifier.$unset && (modifier.$unset['profile.taskInProgress'] == ''));
let allowed = userIdExists && requesterIsLoggedInUser && (progressSet || progressUnset);
let denied = !allowed;
return denied;
i tend to be verbose in logic situations like this, to ensure each condition is easily understood.
btw, why is this not expressed as an allow rule? returning "allow" instead of "!allowed" in a deny seems easier to read, imho.
edit: the allow version simply does a "return allowed;" at the end, instead of bothering with the denied variable.
if you're trying to debug, console.log() out all the vars to see if they're what you expect. if you want, update your question w/ those results and console logs of modifier so it's easier to confirm the logic for progressSet and progressUnset.

Groovy NullObject should be null or not?

This example can be easily tested in the groovy console.
var a is evaluated to not null while b is evaluated to null.
Both are instances of org.codehaus.groovy.runtim.NullObject
def b = null
println b.getClass()
println b == null
def a = null.getClass().newInstance()
println a.getClass()
println a == null
Does anyone knows why?
This is a tricky thing when dealing with reflection code.
Actually I am wondering if this is not a bug. As an explanation... NullObject is a runtime/intermediate kind of Object. If you do anything on null, then NullObject is used. This, and the the implementation of NullObject#equals speaks for a==null returning true. It returns fails, because there is some internal code before that, that is for example determining if compareTo is called instead of equals and such things. Now this piece of code starts with
if (left == right) return true;
if (left == null || right == null) return false;
so null==null will return true, but NullObject==null will return false. On the other hand NullObject should not leak out if possible. Maybe we should fix newInstance() to return null.
I filled http://jira.codehaus.org/browse/GROOVY-5769 for this
In the equals method of NullObject, it only returns true if you are comparing it to null
As an instance of NullObject is not strictly null, it returns false...
Whether NullObject should return true if you call equals against another NullObject is probably a question best asked on the mailing list... I'll have a look and see if I can find any previous question.

Order of evaluation of conditionals in actionscript 3.0 (Flex)

var btn:Button;
if(btn != null && btn.label != '') {
mx.controls.Alert.show("d");
}
In the above if clause, is it guaranteed that the first condition(btn != null) will
be evaluated before the second condition?
Yes - ActionScript performs appropriate short-circuiting for the && operator:
http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary013.html
So not only will it evaluate the expressions in the order you described, it won't bother evaluating the second expression at all if the first one returns false (which is as important a detail as the order of evaluation).
Just as a note, ActionScript also supports short-circuiting the logical or operator (||).
Yes it is. Excerpts from the Adobe livedocs regarding && operator:
&& logical AND Operator:
Usage:
expression1 && expression2
Returns expression1 if it is false or can be converted to false, and expression2 otherwise.

Resources