Anyway here's my problem I have been modifying a whole C++ program to work in C# and I am pretty much done, I have this If statement in the C++ program.
if(info[i].location & 0x8 ||
info[i].location & 0x100||
info[i].location & 0x200)
{
//do work
}
else
{
return
}
And of course when I do this in C# it gives me a "Operator '||' cannot be applied to operands of type 'int' and 'int'" error.
Any clue on what my problem is, Im guessing that C# has got a way of doing this as I am fairly unfamiliar with these old C operators.
Why it fails
Fundamentally it's the same difference as this:
if (someInteger) // C or C++
vs
if (someInteger != 0) // C#
Basically C# is a lot stricter when it comes to logical operators and conditions - it forces you to have use something which is either bool or convertible to bool.
As an aside, that's also why in C# this isn't just a warning, but a full-blown error:
int x = ...;
if (x = 10) // Whoops - meant to be == but it's actually an assignment
If you see comparisons this way round:
if (10 == x)
That's usually developers trying to avoid typos like the above - but it's not needed in C# unless you're really comparing against constant bool values.
Fixing the problem
I suspect you just need:
if (((info[i].location & 0x8) != 0)) ||
((info[i].location & 0x100) != 0)) ||
((info[i].location & 0x200) != 0)))
It's possible that you don't need all of those brackets... but another alternative is just to use one test:
if ((info[i].location & 0x308) != 0)
After all, you're just testing whether any of those three bits are set...
You should also consider using a flags-based enum:
[Flags]
public enum LocationTypes
{
Foo = 1 << 3; // The original 0x8
Bar = 1 << 8; // The original 0x100
Baz = 1 << 9; // The original 0x200
}
Then you could use:
LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if ((info[i].location) & mask != 0)
Or using Unconstrained Melody:
LocationTypes mask = LocationTypes.Foo | LocationTypes.Bar | LocationTypes.Baz;
if (info[i].location.HasAny(mask))
It's pretty much exactly what it says: in C#, || is a logical-only operator and so cannot work on int. You can replace || with | (the bitwise-or which works on ints), but then the entire expression will need to be converted to boolean by comparing it to zero, because in C# the if-statements require a boolean.
Alternatively, you can replace info[i].location & 0x8 with (info[i].location & 0x8 != 0).
Related
Given the following C++ Code:
void Check(DWORD64 ptr)
{
if ( ! (ptr & 0x8000000000000000) )
return;
}
In C# this results in the following Error:
CS0023 Operator '!' cannot be applied to operand of type 'ulong'
How do I bitwise check the ptr parameter in C#?
Comparing to not 0?
void Check(ulong ptr)
{
if ((ptr & 0x8000000000000000) != 0)
return;
}
or checking for 0?
void Check(ulong ptr)
{
if ((ptr & 0x8000000000000000) == 0)
return;
}
Googleing for this questions leads to all sorts of answers on different bitwise operations but I couldn't find an answer for this specific negation with exclemation mark.
When operator ! "logical not" is applied to a numeric value in C or C++, it produces a result as follows:
1 if its operand is zero
0 otherwise
C's conditional statement if interprets 0 as "false" and any non-zero value, including 1, as "true". Therefore, your second option is correct.
The second one. C++ would treat any nonzero value as true, so the ! check on an integer was effectively equivalent to !(value != 0) or (value==0)
I was browsing around stack overflow and I encountered this question:
check for duplicate filename when copying files in C#
In this question, this little gem existed:
int i = +1
I have never seen this syntax before. So I opened up the interactive C# window in visual studio:
Microsoft (R) Roslyn C# Compiler version 1.3.4.60902
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> int i = +1;
> i
1
> +1 == 1
true
Is this similar to +=? Is this some new syntax? What is this operator? How is it different than a normal variable declaration?
That's the unary plus operator. From the documentation:
The result of a unary + operation on a numeric type is just the value of the operand.
In most sane contexts1 where you're writing code, it'll be optional (+1 is the same as 1 if we're writing literals).
It mostly exists for symmetry with the unary minus operator.
Most of the time, you'll not write code containing it, but if you're generating code it can be handy to be able to apply a unary operator either way2.
It has no relation to +=.
1Insane code could override this operator for custom types and make it more than a no-op. But I'd love to understand a use case where it makes code more understandable, which should be the main aim of most code.
2E.g. imagine you're chaining a set of operations together and for each additional element, you wish to change the sign of the overall result. This lets you just store an operator and apply it blindly when you finally decide to output a result
For for all signed numeric types the positive-sign is optional. So,
+1 == (+1) == 1
+1.0 == (+1.0) == 1.0
+1L == (+1L) == 1L
+1.0m == (+1.0m) == 1.0m
Do not confuse
int i = +1; // Assigns 1
which is the same as
int i = (+1); // Assigns 1
or simply
int i = 1; // Assigns 1
with
int i += 1; // INCREMENT!
which increments i.
In C# terms there is a binary + operator (the addition operator as in int i = 3 + 4;) and a unary + operator (the plus sign as in int i = +1;).
Think of it the way you think of
int i = -1
and it becomes obvious
so I'm trying to make a code with &&. However, when I put that in, it said that I couldn't apply the operand to it.
In specific, it reads: Operator "&&" cannot be applied to operands of type 'Server.Enums.PokemonType' and 'Server.Enums.PokemonType'
However, I need to be able to link these two things so I can make the code be two PokemonTypes. So is there any alternative or work-around for not being able to use &&?
If you need it, this is my code:
case 225:
{
//Flying Press -- INCOMPLETE, needs Flying-type
setup.Move.Element = Enums.PokemonType.Fighting && setup.Move.Element = Enums.PokemonType.Flying;
if (setup.Defender.VolatileStatus.GetStatus("Minimize") != null)
{
setup.Multiplier *= 2;
setup.Move.Accuracy = -1;
}
}
break;
The system defined && operator only supports boolean operands. The & operator will work for enums (because it also works on all integer types, which the enums are based on). Of course, if you want an enum that represents the combination of two flag values then you'll want to OR them together (using |), not AND them together.
To add multiple values to a enum variable you need to declare the enum with [Flags] attribute.
So your enum would be:
[Flags]
public enum PokemonType
{
Fighting = 1 << 0,
Flying = 1 << 1,
Normal = 1 << 2,
Dragon = 1 << 3,
}
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap
Then assign using Enums.PokemonType.Fighting | Enums.PokemonType.Flying so it is possible to track all values assigned to it later.
I've always believed that using conditional boolean operators (a.k.a. short-circuiting) in stead of regular boolean operators doesn't affect the outcome of an expression.
var result = true | false & false;
has the same result as
var result = true || false && false
Both expressions result in true.
But what if I would mix regular and conditional operators?
var result1 = true || false & false;
var result2 = true | false && false;
What would you expect? I would expect these to still return true. But that isn't the case. Result2 will be false!
I know this is because of the operator precedence. The precedence order is & | && ||. This seems counter intuitive to me. I'd expect an order of & && | ||, in which case all results would be the same (I think).
So I guess my real question isn't if short-circuiting can change the result. The question is why the order of precedence is such that short-circuiting can change the result.
var result2 = true | false && false;
Is calculated as:
var result2 = (true | false) && false;
Because | comes before &&. Now (true | false) evaluates to true, and true && false is false.
As for the why, see this question:
The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language...
The precedence of the operators in question seems to be copied directly from the precedence in the C (and C++) programming language.
Now in C, they don't use distinct types for integers and booleans. For example they could write:
if (i | j && x > 0) // cf. the result2 of your question
and this should mean "the integers i and j bitwise or'ed gives something nonzero AND the number x is positive". So | and & are supposed to be mostly used when the operands are thought of as integers (many-bit numbers), and || and && are supposed to be mostly used when the operands are thought of as booleans.
So it might seem natural in C that | binds more strictly than &&.
In C# we have a higher degree of type safety, and there are no conversions from Int32 to Boolean or from Boolean to Int32. Therefore it is no longer possible to "mix" things, and the precedence no longer feels natural.
I guess in theory in C#, one could make the operator
public static bool operator |(bool b, bool c)
have a different precedence than the operator
public static int operator |(int i, int j)
but it wouldn't really make things better?
I think it's very rare that people use boolean non-short-circuit operators like | and short-circuit operators like && in the same expression, but when they do, they should either be very careful about precedence, or just put the parenthesis () there (it will also make the intention more clear).
The & and | operators evaluate both arguments (which could involve calling a method) and then return the result of the and- or or-operation.
The && and || operators only evaluate their arguments to the point where the final result is determined completely.
For example:
true | SomeMethod() and
false & SomeMethod() calls the SomeMethod() function
true || SomeMethod() and
false && SomeMethod() don't.
trueand false in this example could also be variables of course, I simply used constant to make the example easier to understand.
I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?
Just like the & and && operator, the double Operator is a "short-circuit" operator.
For example:
if(condition1 || condition2 || condition3)
If condition1 is true, condition 2 and 3 will NOT be checked.
if(condition1 | condition2 | condition3)
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
if(class != null && class.someVar < 20)
If class is null, the if-statement will stop after class != null is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.
No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions, and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the | and & operator though: Bitwise Operations.
|| is the logical OR operator. It sounds like you basically know what that is. It's used in conditional statements such as if, while, etc.
condition1 || condition2
Evaluates to true if either condition1 OR condition2 is true.
| is the bitwise OR operator. It's used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:
A = 01010101
B = 10101010
A | B = 11111111
A = 00000001
B = 00010000
A | B = 00010001
A = 10001011
B = 00101100
A | B = 10101111
Hopefully that makes sense.
So to answer the last two questions, I wouldn't say there are any caveats besides "know the difference between the two operators." They're not interchangeable because they do two completely different things.
One is a "bitwise or".
10011b | 01000b => 11011b
The other is a logic or.
true or false => true
Good question. These two operators work the same in PHP and C#.
| is a bitwise OR. It will compare two values by their bits. E.g. 1101 | 0010 = 1111. This is extremely useful when using bit options. E.g. Read = 01 (0X01) Write = 10 (0X02) Read-Write = 11 (0X03). One useful example would be opening files. A simple example would be:
File.Open(FileAccess.Read | FileAccess.Write); //Gives read/write access to the file
|| is a logical OR. This is the way most people think of OR and compares two values based on their truth. E.g. I am going to the store or I will go to the mall. This is the one used most often in code. For example:
if(Name == "Admin" || Name == "Developer") { //allow access } //checks if name equals Admin OR Name equals Developer
PHP Resource: http://us3.php.net/language.operators.bitwise
C# Resources: http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx
http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx
& - (Condition 1 & Condition 2): checks both cases even if first one is false
&& - (Condition 1 && Condition 2): dosen't bother to check second case if case one
is false
&& - operator will make your code run faster, professionally & is rarely used
| - (Condition 1 | Condition 2): checks both cases even if case 1 is true
|| - (Condition 1 || Condition 2): dosen't bother to check second case if first
one is true
|| - operator will make your code run faster, professionally | is rarely used
Simple example in java
public class Driver {
static int x;
static int y;
public static void main(String[] args)
throws Exception {
System.out.println("using double pipe");
if(setX() || setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
System.out.println("using single pipe");
if(setX() | setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
}
static boolean setX(){
x=5;
return true;
}
static boolean setY(){
y=5;
return true;
}
}
output :
using double pipe
x = 5
y = 0
using single pipe
x = 5
y = 5
By their mathematical definition, OR and AND are binary operators; they verify the LHS and RHS conditions regardless, similarly to | and &.
|| and && alter the properties of the OR and AND operators by stopping them when the LHS condition isn't fulfilled.
The single pipe, |, is one of the bitwise operators.
From Wikipedia:
In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes).
For bitwise | and Logicall ||
OR
bitwise & and logicall &&
it means if( a>b | a==0)
in this first left a>b will be evaluated and then a==0 will be evaluated then | operation will be done
but in|| if a>b then if wont check for next RHS
Similarly for & and &&
if(A>0 & B>0)
it will evalue LHS and then RHS then do bitwise & but
in(A>0 && B>0)
if(A>0) is false(LHS) it will directly return false;
The | operator performs a bitwise OR of its two operands (meaning both sides must evaluate to false for it to return false) while the || operator will only evaluate the second operator if it needs to.
http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx
http://msdn.microsoft.com/en-us/library/6373h346(VS.71).aspx
The singe pipe "|" is the "bitwise" or and should only be used when you know what you're doing. The double pipe "||" is a logical or, and can be used in logical statements, like "x == 0 || x == 1".
Here's an example of what the bitwise or does: if a=0101 and b=0011, then a|b=0111. If you're dealing with a logic system that treats any non-zero as true, then the bitwise or will act in the same way as the logical or, but it's counterpart (bitwise and, "&") will NOT. Also the bitwise or does not perform short circuit evaluation.
A single pipe (|) is the bitwise OR operator.
Two pipes (||) is the logical OR operator.
They are not interchangeable.