This question already has answers here:
Double Negation in C++
(14 answers)
Closed 9 years ago.
Sometimes, I saw the following code:
if ( !!on_debugging )
which is the same as
if ( on_debugging )
I don't understand why these two !s are used. Is there any kind of difference?
!!a is almost equivalent to a. It converts it to a boolean value.
Usually this does not make a difference, but sometimes it does.
#include <iostream>
int a(int x) {
return 1;
}
int a(bool x) {
return 2;
}
int main() {
std::cout << a(0) << std::endl; //prints 1
std::cout << a(!!0) << std::endl; //prints 2
std::cout << -1 << std::endl; //prints -1
std::cout << !!-1 << std::endl; //prints 1
}
In your case, there is no difference, unless there is overloading. (But even if there is overloading, I hope there is no difference.)
(FYI, this is done even more commonly in Javascript because of its types, e.g. false != null but false == !!null. I include this comment because you tagged your question with C, C++, and Java, and Javascript shares similar syntax.)
If operator! is not overloaded, the two statements are equivalent.
Where !! might be useful is if you need to change a zero / non-zero value, or a nullptr / non-null pointer value into a 0/1 value in an integer expression.
For a (dubious) example, the following loop counts the number of non-zero elements in a vector:
for (size_t i = 0; i != v.size(); i++)
count += !!v[i];
You will sometimes see !! in bit-level hacks as a result. But in the if statement you show above? Unless operator! is overloaded, that's not a useful operation.
There must be some form of operator overloading else, it means the same.
Take this as an live example:
#include <stdio.h>
int main(void) {
int a = 5;
printf("%d\n", a);
printf("%d\n", !!a); // will print 1
return 0;
}
The main difference is a silly-warning from Visual C++.
Secondary (rare) differences include the case where you have an operator!, and the case where the argument is used in a non-boolean context, e.g. arithmetic.
Double ! simplily means a unary NOT and another unary not. See it as (!(!on_debugging))
Yes, you are right, most of the time the results is the same as on_debugging. I think this is for preciseness or strictness to use !! because the ! operator only returns integer 0 or 1, which corresponds to false and true. While the variable can be anything of int and point type.
For Java !!on_debugging is the opposite of !!!on_debugging.
You can negate stuff as often as you want, thus there is no difference between on_debugging and !!on_debugging.
Also see Java Language Specification for this operator:
The type of the operand expression of the unary ! operator must be
boolean or Boolean, or a compile-time error occurs.
(see JLS 15.15.6).
Related
Just had an interesting thought. In languages like C# and Java, I know that when it comes to incrementing and decrementing, you can do a post, or pre-increment/decrement. Like this:
int a = 5;
Console.WriteLine(a++); // Would print out 5,
// And then increment a to 6
Console.WriteLine(++a); // Would then print out 7 because
// it increments a before printing it out
But, I was wondering if there is any such thing where one might do something like this:
int a = 5;
Console.WriteLine(a += 5); // Would print out 5,
// And then increment a to 10
Console.WriteLine(a =+ 5); // (Or something along those lines)
// To print out 15 at this point
Just interested and didn't really know where or how to look for the answer, so wondered if anyone on SO would know anything more about it. Thanks!
Edit: Added my question from the comments
Where exactly are a += 5 and a =+5 defined? I've never seen the second in use. Does it exist at all...? Do they compile to the same thing?
In the old days, the C language offered this syntax as a shortcut for adding or subtracting a value from a variable.
a =+ 5;
b =- 5;
But early on in the life of C, dmr (of blessed memory) and ken deprecated that syntax in favor of
a += 5;
b -= 5;
for precisely the same purpose, because it's far too easy to write b=-5 which means something entirely different from b -= 5. This "experienced" programmer remembers rewriting a bunch of code to match the new language spec.
So there has never been pre- or post- increment semantics in those constructions like there is in a++ or --b.
No. a += 5 isn't a post increment. It's an increment.
a++ is post-increment. And ++a is pre-increment.
The following prints the required results but is not exactly beautiful code:
int a = 5;
System.out.println(a+=5);
System.out.println((a+=5)-5);
System.out.println(a);
Prints:
10, 10, 15
a+=5 returns the value of a after the increment. (a+=5)-5 increments a and returns its value before the increment.
a=+5 just compiles to a=5. This performs assignment and the unary plus operator. It is akin to doing a=-5 (a equals negative 5).
System.out.println(+5);
Prints:
5
In C# the equivalent code generates the same output:
int a = 5;
Console.WriteLine(a+=5);
Console.WriteLine((a+=5)-5);
Console.WriteLine(a);
Console.WriteLine(+5);
Prints:
10, 10, 15, 5
There is no such operator in any language that I know of, but you can write your own C# function to do the same thing!
static void postAdd<T>(ref T lhs, T rhs) {
T saved = lhs;
lhs += rhs;
return saved;
}
This is not possible in Java because Java does not support pass-by-reference with ref.
Console.WriteLine(a+=5);
Is perfectly legal in the langauge. It is a sort of pre-increment operator in that it will increment the variable a before returning the value to the WriteLine call.
=+ isn't a valid operator since it isn't defined by the C# standard. All of the C# operators can be found on this page: https://msdn.microsoft.com/en-us/library/ewkkxkwb.aspx
Its not possible to create your own operators, because the compiler would have to know how to make expression trees or parse the line to generate the IL. The aside to this is that, by a lot of work and especially with the release of Rosyln, you could in theory make your own language (like IronPython) that had those operators.
The closest that you can come to your own operator are things like extension methods, for example:
public class Extensions
{
public static int AddMul(this int x, int add, int mull)
{
return x * mull + add;
}
}
which would be used like:
int x = 4;
int y = x.AddMul(2, 3); //y now equals 14
Does LargeInteger have an equivalent to BigInteger's testBit?
If not, how can testBit be performed on a LargeInteger?
I don't yet have the necessary skills to reproduce ((this & (1<<n)) != 0).
I tried making a method by just copying & pasting the above code referenced from the docs:
static boolean testBit(int n){
return ((this & (1<<n)) != 0);
}
However, the compiler reports:
error: non-static variable this cannot be referenced from a static context
return ((this & (1<<n)) != 0);
^
error: bad operand types for binary operator '&'
return ((this & (1<<n)) != 0);
^
This is the best I can come up with given the API:
static boolean testBit(LargeInteger i, int n) {
return i.shiftRight(n).isOdd();
}
n is the position of the bit to be tested.
I assume you put this method in some utility class.
Explanation
Normally, you would do num & (1 << pos) to extract the bit at pos position:
???????x?????
0000000100000
-------------
0000000x00000
If the whole thing is 0 then x is 0; otherwise, x is 1.
In the method above, I do num >> pos:
???????x?????
-------------
????????????x
We know that a binary number is odd when its least significant bit is 1, and it is even when its least significant bit is 0.
So if the number after right-shifting is odd, we know the bit is 1; if even, we know the bit is 0.
This question already has answers here:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)? [duplicate]
(6 answers)
Closed 9 years ago.
[I thought this would have been asked already, but I can't find an answer].
When writing an if statement, should the thing I'm comparing against come first or second? (I am specifically curious about both C / C++ and Java).
Does it matter, or is it just stylistic? (Convention seems to be "variable first, value second").
Consider the following code:
#include <iostream>
int main() {
int x = 5;
if ( 5 == x ) {
std::cout << "X == 5, true." << std::endl;
}
if ( x == 5 ) {
std::cout << "5 == X, true." << std::endl;
}
return 0;
}
which outputs:
X == 5, true.
5 == X, true.
so there doesn't appear to be any difference. Are there subtleties I'm missing?
These are called Yoda Conditions and to my knowledge the main idea is to guard against accidental assignment (i.e. you can't assign to literals).
Yes, worth mentioning that something like if (a = 5) where a is not a bool is not allowed in languages such as Java (though OK in C/C++), but as the Wikipedia article points out it is still possible to guard against unwanted behavior:
It can also solve some types of unsafe null behavior.
String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java
With Yoda Conditions:
String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This is false, as expected
Putting the constant first (aka "Yoda style") prevents problems from a simple typo:
if (x = 5) // if (x == 5) was intended
...still compiles but does the wrong thing (though most current compilers will warn about the problem).
if (5 = x) // if (5 == x) was intended
...absolutely cannot compile on anything even approaching a properly functioning compiler.
No, there is no difference. It doesn't matter. Do whatever you like. Personally I'd do:
x == 5
Because it reads better (or so I think). 5 == x just doesn't sound right. But again, personal opinion.
I think you'll find that most people do x == 5 because you are comparing x, rather than comparing 5.
Both are ok.
But it is more accepted to do so when the parameter on left side.
example:
if ( x == 5 )
Anyway. it doesn't matter, do whatever you pleased and feel more comfortable with.
In most cases you'll find the common practice is to have the variable come first because the operator == means assignment and here you are assigning the value 5 so it only makes sense to have the variable come first.
Your if statement should then look like this:
if ( 5 == x ) {
std::cout << "X == 5, true." << std::endl;
}
(a > b) & (c < d), the components are evaluated left to right, so (a >
b) is evaluated first. If (a > b) is false, the entire expression is
false regardless of the result of the component (r < d). Nevertheless,
the component (c < d) will still be evaluated. However, in the
expression (a > b) && (c < d), the component (c < d) will not be
evaluated if (a > b) evaluates to false. This is known as short
circuiting.
Came across this paragraph in a Java book. I have been programming in various languages before, but I've never found a need for '&'. Why would one want to evaluate the second statement if it's known that the end result is not affected by it? Is there any use for it; does it come due to historical reasons?
Same question applies to | and || as well.
The && operator is defined by the Java Language Specification to perform short-circuit evaluation.
However, the & operator is not, even when applied to boolean arguments.
You could exploit this if one of the arguments had side-effects that you did not want short-circuited. However, in my experience this is uncommon, and you'd face the risk of someone "fixing" it. It would be better separated into steps. For example, instead of:
if ( foo() & bar() ) {... }
you could say:
boolean isFoo = foo();
boolean isBar = bar();
if ( isFoo && isBar ) { ... }
if you expect your code to be under attack from timing attacks you want the least amount of branches (conditional execution paths) possible, this is one way to eliminate them
The difference between '&' and '&&' is not well-known and that example from the book doesn't help much.
Here's another example to show how short-circuiting work (using horrible methods having side-effects, but that's not the point).
Imagine you have this:
private int cnt;
private boolean a() {
cnt++;
return false;
}
private boolean b() {
cnt++;
return false;
}
If you execute the following:
cnt = 0;
if ( a() && b() ) {}
System.out.println( cnt );
It shall print 1.
While if you execute the following:
cnt = 0;
if ( a() & b() ) {}
System.out.println( cnt );
It shall print 2. Because in the latter case b() must be evaluated as per the language specs while in the first case b() must not be evaluated, as per the language specs.
You can use & in situations where you have to evaluate both subexpressions. For example, if they both have side effects that are observable by the rest of your application.
Perhaps the 2nd evaluation is in the form of an assignment statement or method call, in which case you might want it to execute. I wouldn't use bitwise operators in place of logical operators like this tho. If you need something to execute passed &&, then do it prior to your logical statement and store the result in a variable.
if(0 != ((a > b) ? 1 : 0) & ((c < d) ? 1 : 0)) {
// but really... (a > b) && (c < d), assuming no side-effects
}
...just use the logical operators (&& and ||) for conditions ;-) That is what they were designed for. If non-shortcircuit behavior is required, then restructure the code accordingly.
I think I have seen one case that had a somewhat valid use of & in this context, but I do not recall what it was so I mustn't have found it that valid ;-) In languages like C/C++ where there is no discreet "boolean" type, the (input) and result of & can be treated such that 0 -> false and non-0 -> true. As can be seen, however, Java has to jump through some fun to get bool -> int -> bool.
The only justification for a bit-wise operator is, well, bit-wise operations, IMOHO. Bit-wise operators are most useful when performing some sort of encoding including "bit fields" and "bit masks". They are also useful when dealing with fun arising from Java's signed-only bytes, etc.
I think the bigger (only?) point to take away is that && and || are short-circuiting -- they are actually the only operators with this behavior (arguments over ?: excluded); the rest is just to explain the eager-behavior of bit-wise operators. This just goes to re-enforce the rule: do not cause side-effects in conditionals (outside of a few well-accepted idioms, but even then, keep it simple).
Happy coding.
Examples of bit-wise usage:
Imagine the use of flags which are stored into a single "integer" slot in a serialized format:
int flags = 0;
if (this.encypted) {
flags |= EncryptedMode;
}
out.write(flags);
// later on
int flags = in.readInt();
this.encrypted = (flags & EncryptedMode) != 0;
Reading the "unsigned value" of a byte:
byte[] data = {-42, ...}; // read in from file or something
int unsignedByte = data[0] & 0xFF;
Your book is confusing things. For the most part, you will only use '&&' and '||'. The single ones, '&' and '|', are bitwise operators - you can read more about them here: http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
The use of a non-short-circuit operator may speed up performance-critical code by avoiding branch mis-prediction stalls, which could easily amount to a dozen or more clock cycles.
I have a long set of comparisons to do in Java, and I'd like to know if one or more of them come out as true. The string of comparisons was long and difficult to read, so I broke it up for readability, and automatically went to use a shortcut operator |= rather than negativeValue = negativeValue || boolean.
boolean negativeValue = false;
negativeValue |= (defaultStock < 0);
negativeValue |= (defaultWholesale < 0);
negativeValue |= (defaultRetail < 0);
negativeValue |= (defaultDelivery < 0);
I expect negativeValue to be true if any of the default<something> values are negative. Is this valid? Will it do what I expect? I couldn't see it mentioned on Sun's site or stackoverflow, but Eclipse doesn't seem to have a problem with it and the code compiles and runs.
Similarly, if I wanted to perform several logical intersections, could I use &= instead of &&?
The |= is a compound assignment operator (JLS 15.26.2) for the boolean logical operator | (JLS 15.22.2); not to be confused with the conditional-or || (JLS 15.24). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively.
In other words, for boolean b1, b2, these two are equivalent:
b1 |= b2;
b1 = b1 | b2;
The difference between the logical operators (& and |) compared to their conditional counterparts (&& and ||) is that the former do not "shortcircuit"; the latter do. That is:
& and | always evaluate both operands
&& and || evaluate the right operand conditionally; the right operand is evaluated only if its value could affect the result of the binary operation. That means that the right operand is NOT evaluated when:
The left operand of && evaluates to false
(because no matter what the right operand evaluates to, the entire expression is false)
The left operand of || evaluates to true
(because no matter what the right operand evaluates to, the entire expression is true)
So going back to your original question, yes, that construct is valid, and while |= is not exactly an equivalent shortcut for = and ||, it does compute what you want. Since the right hand side of the |= operator in your usage is a simple integer comparison operation, the fact that | does not shortcircuit is insignificant.
There are cases, when shortcircuiting is desired, or even required, but your scenario is not one of them.
It is unfortunate that unlike some other languages, Java does not have &&= and ||=. This was discussed in the question Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=).
It's not a "shortcut" (or short-circuiting) operator in the way that || and && are (in that they won't evaluate the RHS if they already know the result based on the LHS) but it will do what you want in terms of working.
As an example of the difference, this code will be fine if text is null:
boolean nullOrEmpty = text == null || text.equals("")
whereas this won't:
boolean nullOrEmpty = false;
nullOrEmpty |= text == null;
nullOrEmpty |= text.equals(""); // Throws exception if text is null
(Obviously you could do "".equals(text) for that particular case - I'm just trying to demonstrate the principle.)
You could just have one statement. Expressed over multiple lines it reads almost exactly like your sample code, only less imperative:
boolean negativeValue
= defaultStock < 0
| defaultWholesale < 0
| defaultRetail < 0
| defaultDelivery < 0;
For simplest expressions, using | can be faster than || because even though it avoids doing a comparison it means using a branch implicitly and that can be many times more expensive.
Though it might be overkill for your problem, the Guava library has some nice syntax with Predicates and does short-circuit evaluation of or/and Predicates.
Essentially, the comparisons are turned into objects, packaged into a collection, and then iterated over. For or predicates, the first true hit returns from the iteration, and vice versa for and.
If it is about readability I've got the concept of separation tested data from the testing logic. Code sample:
// declare data
DataType [] dataToTest = new DataType[] {
defaultStock,
defaultWholesale,
defaultRetail,
defaultDelivery
}
// define logic
boolean checkIfAnyNegative(DataType [] data) {
boolean negativeValue = false;
int i = 0;
while (!negativeValue && i < data.length) {
negativeValue = data[i++] < 0;
}
return negativeValue;
}
The code looks more verbose and self-explanatory. You may even create an array in method call, like this:
checkIfAnyNegative(new DataType[] {
defaultStock,
defaultWholesale,
defaultRetail,
defaultDelivery
});
It's more readable than 'comparison string', and also has performance advantage of short-circuiting (at the cost of array allocation and method call).
Edit:
Even more readability can be simply achieved by using varargs parameters:
Method signature would be:
boolean checkIfAnyNegative(DataType ... data)
And the call could look like this:
checkIfAnyNegative( defaultStock, defaultWholesale, defaultRetail, defaultDelivery );
It's an old post but in order to provide a different perspective for beginners, I would like give an example.
I think the most common use case for a similar compound operator would be +=. I'm sure we all wrote something like this:
int a = 10; // a = 10
a += 5; // a = 15
What was the point of this? The point was to avoid boilerplate and eliminate the repetitive code.
So, next line does exactly the same, avoiding to type the variable b1 twice in the same line.
b1 |= b2;
List<Integer> params = Arrays.asList (defaultStock, defaultWholesale,
defaultRetail, defaultDelivery);
int minParam = Collections.min (params);
negativeValue = minParam < 0;
|| logical boolean OR
| bitwise OR
|= bitwise inclusive OR and assignment operator
The reason why |= doesn't shortcircit is because it does a bitwise OR not a logical OR.
That is to say:
C |= 2 is same as C = C | 2
Tutorial for java operators