When checking if a integer is the same or above a current number.. so I type
if (5 => 6) { //Bla }
but it shows this as a error. Why? Isn't it exactly the same as
if (5 >= 6) { //Bla }
The reason why it does not work is because => is not equivalent to >=.
=> is used in a lambda expression. Like :
(int x, string s) => s.Length > x
I do agree it is annoying. Before lambda expressions I used to get it wrong sometimes. Now I always know that one (=>) is a lambda expression and and other (>=) is the greater than equal to sign
Because the operator is >= not =>.
The writers of the language could have chosen either syntax, but had to choose one. Having two operators meaning the same thing would be confusing at best.
However, the operator is read "greater than or equal to" so it does make sense that the > symbol is first.
Also => is now used for Lambda expressions.
Because => is meant for lambda expressions:
Action<object> print = o => Console.WriteLine(o);
print(123);
Besides, you don't say "equal to or greater than", which is what => would have been pronounced as otherwise.
The confusion here is that you're assuming >= is two operators smooshed together. In fact, it's only one operator with two characters, much the same as tons of other operators (+=, *=, -=, etc).
Why should it be? =! is not the same as != either. This is a part of the languages syntax.
In this specific case, => is also used for lambda expressions so it has another purpose.
Because it is called greater or equal to. Not equal or greater than. Simple uh?
In C# the greater than or less than sign must come BEFORE the equal sign. It is just part of the syntax of the language.
Because => stands for Lambda expressions in c#.
>= stands for greater than or equal to, as you already know.
The syntax is such that you have to use >= while comparing two entities. Also just additionally you can notice that even a space between them will give errors - > =
No, it is not this same. Correct operator in c# is >= for comparission and => for lambda expression.
#Barry's answer is probably the most insightful of the lot here. A single operator does not mean a single character; the fact that > and = combine to form >= does not mean that it's doing both > and =; it's doing a single operation. The fact that the defined operator for that operation includes the characters for two other similar operations is irrelevent.
I suppose if you really wanted to you could override it so that both >= and => worked the same way -- C# does allow operator overrides. But it would be a bad idea because as others have already said, => is actually in use for other purposes.
Related
Assume myObj is null. Is it safe to write this?
if(myObj != null && myObj.SomeString != null)
I know some languages won't execute the second expression because the && evaluates to false before the second part is executed.
Yes. In C# && and || are short-circuiting and thus evaluates the right side only if the left side doesn't already determine the result. The operators & and | on the other hand don't short-circuit and always evaluate both sides.
The spec says:
The && and || operators are called the conditional logical operators. They are also called the “shortcircuiting” logical operators.
...
The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true
...
The operation x && y is evaluated as (bool)x ? (bool)y : false. In other words, x is first evaluated and converted to type bool. Then, if x is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.
(C# Language Specification Version 4.0 - 7.12 Conditional logical operators)
One interesting property of && and || is that they are short circuiting even if they don't operate on bools, but types where the user overloaded the operators & or | together with the true and false operator.
The operation x && y is evaluated as T.false((T)x) ? (T)x : T.&((T)x, y), where
T.false((T)x) is an invocation of the operator false declared in T, and T.&((T)x, y) is an invocation of the selected operator &. In addition, the value (T)x shall only be evaluated once.
In other words, x is first evaluated and converted to type T and operator false is invoked on the result to determine if x is definitely false.
Then, if x is definitely false, the result of the operation is the value previously computed for x converted to type T.
Otherwise, y is evaluated, and the selected operator & is invoked on the value previously computed for x converted to type T and the value computed for y to produce the result of the operation.
(C# Language Specification Version 4.0 - 7.12.2 User-defined conditional logical operators)
Yes, C# uses logical short-circuiting.
Note that although C# (and some other .NET languages) behave this way, it is a property of the language, not the CLR.
I know I'm late to the party, but in C# 6.0 you can do this too:
if(myObj?.SomeString != null)
Which is the same thing as above.
Also see:
What does question mark and dot operator ?. mean in C# 6.0?
Your code is safe - && and || are both short-circuited. You can use non-short-circuited operators & or |, which evaluate both ends, but I really don't see that in much production code.
sure, it's safe on C#, if the first operand is false then the second is never evaluated.
It is perfectly safe. C# is one of those languages.
In C#, && and || are short-circuited, meaning that the first condition is evaluated and the rest is ignored if the answer is determined.
In VB.NET, AndAlso and OrElse are also short-circuited.
In javaScript, && and || are short-circuited too.
I mention VB.NET to show that the ugly red-headed step-child of .net also has cool stuff too, sometimes.
I mention javaScript, because if you are doing web development then you probably might also use javaScript.
Yes, C# and most languages compute the if sentences from left to right.
VB6 by the way will compute the whole thing, and throw an exception if it's null...
an example is
if(strString != null && strString.Length > 0)
This line would cause a null exception if both sides executed.
Interesting side note. The above example is quite a bit faster than the IsNullorEmpty method.
I have seen some code which uses the <= operator. Can you explain what is the use of having lambda in reverse direction?
That's just less than or equal. I don't think C# lambdas work like that. It's too early in the morning. You need coffee.
That's not a lambda at all. That's less than or equal to
(Except when it's actually a reverse lambda)
It is only used as 'less than or equal to' operation, as in:
if (i <= 5) {
// ...
}
Situation: condition check in C++ or C# with many criteria:
if (condition1 && condition2 && condition3)
{
// Do something
}
I've always believed the sequence in which these checks are performed is not guaranteed. So it is not necessarily first condition1 then condition2 and only then condition3. I learned it in my times with C++. I think I was told that or read it somewhere.
Up until know I've always written secure code to account for possible null pointers in the following situation:
if ((object != null) && (object.SomeFunc() != value))
{
// A bad way of checking (or so I thought)
}
So I was writing:
if (object != null)
{
if (object.SomeFunc() != value)
{
// A much better and safer way
}
}
Because I was not sure the not-null check will run first and only then the instance method will be called to perform the second check.
Now our greatest community minds are telling me the sequence in which these checks are performed is guaranteed to run in the left-to-right order.
I'm very surprised. Is it really so for both C++ and C# languages?
Has anybody else heard the version I heard before now?
Short Answer is left to right with short-circuit evaluation. The order is predictable.
// perfectly legal and quite a standard way to express in C++/C#
if( x != null && x.Count > 0 ) ...
Some languages evaluate everything in the condition before branching (VB6 for example).
// will fail in VB6 if x is Nothing.
If x Is Not Nothing And x.Count > 0 Then ...
Ref: MSDN C# Operators and their order or precedence.
They are defined to be evaluated from left-to-right, and to stop evaluating when one of them evaluates to false. That's true in both C++ and C#.
I don't think there is or has been any other way. That would be like the compiler deciding to run statements out of order for no reason. :) Now, some languages (like VB.NET) have different logical operators for short-circuiting and not short-circuiting. But, the order is always well defined at compile time.
Here is the operator precedence from the C# language spec. From the spec ...
Except for the assignment operators,
all binary operators are
left-associative, meaning that
operations are performed from left to
right. For example, x + y + z is
evaluated as (x + y) + z.
They have to be performed from left to right. This allows short circuit evaluation to work.
See the Wikipedia article for more information.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Are there any understanding / maintainability issues that result from code like
inVar1 == 0 ? NULL : v.push_back(inVar1);
inVar2 == 0 ? NULL : v.push_back(inVar2);
and so forth.
The possibly confusing idea is using the ternary operator for program flow rather than variable assignment, which is the usual explanation.
I haven't seen coding standards at work that address this usage, so while I'm comfortable doing this I'd like to find out if there is a good reason not to.
I think it's confusing and a lot harder to read than simply typing;
if (inVar != 0)
v.push_back(inVar);
I had to scan your example several times to figure out what the result would be with any certainty. I'd even prefer a single-line if() {} statement than your example - and I hate single-line if statements :)
The ternary operator is meant to return a value.
IMO, it should not mutate state, and the return value should be used.
In the other case, use if statements. If statements are meant to execute code blocs.
The ternary is a good thing, and I generally promote it's usage.
What you're doing here however tarnishes it's credibility. It's shorter, yes, but it's needlessly complicated.
I think this should be avoided. You could use a 1-line if statement in its place.
if(inVar1 != 0) v.push_back(inVar1);
Compilers these days will make an if as fast as a ternary operator.
You goal should be how easy is it for another software developer to read.
I vote for
if ( inVar != 0 )
{
v.push_back( inVar );
}
why the brackets...because one day you may want to put something else in there and the brackets are pre-done for you. Most editors these days will put them in anyway.
Your use of the ternary operator gains you nothing and you hurt the codes readability.
Since the ternary operator returns a value that you are not using it is odd code. The use of an if is much more clear in a case like yours.
As litb mentioned in the comments, this isn't valid C++. GCC, for example, will emit an error on this code:
error: `(&v)->std::vector<_Tp, _Alloc>::push_back [with _Tp = int, _Alloc =
std::allocator<int>](((const int&)((const int*)(&inVar1))))' has type `void'
and is not a throw-expression
However, that can be worked around by casting:
inVar1 == 0 ? (void)0 : v.push_back(inVar1);
inVar2 == 0 ? (void)0 : v.push_back(inVar2);
But at what cost? And for what purpose?
It's not like using the ternary operator here is any more concise than an if-statement in this situation:
inVar1 == 0 ? NULL : v.push_back(inVar1);
if(inVar1 != 0) v.push_back(inVar1);
While, in practice, I agree with the sentiments of those who discourage this type of writing (when reading, you have to do extra work to scan the expression for its side effects), I'd like to offer
!inVar1 ?: v.push_back(inVar1);
!inVar2 ?: v.push_back(inVar2);
...if you're going for obscure, that is. GCC allows x ?: y in place of x ? x : y. :-)
I use ternary operator when I need to call some function with conditional arguments - in this case it is better then if.
Compare:
printf("%s while executing SQL: %s",
is_sql_err() ? "Error" : "Warning", sql_msg());
with
if (is_sql_err())
printf("Error while executing SQL: %s", sql_msg());
else
printf("Warning while executing SQL: %s", sql_msg());
I find the former is more appealing. And it complies to DRY principle, unlike latter - you don't need to write two nearly identical lines.
I think you would be better served in doing a proper if structure. I even prefer to always have braces with my if structures, in the event I have to add lines later to the conditional execution.
if (inVar != 0) {
v.push_back(inVar);
}
I think that sometimes the ternary are a necessary evil in initializer lists for constructors. I use them mostly for constructors where I want to allocate memory and set some pointer to point at it before the body of the constructor.
An example, suppose you had an integer storage class that you wanted to have take a vector as an input but the internal representation is an array:
class foo
{
public:
foo(std::vector<int> input);
private:
int* array;
unsigned int size;
};
foo:foo(std::vector<int> input):size(input.size()), array( (input.size()==0)?
NULL : new int[input.size])
{
//code to copy elements and do other start up goes here
}
This is how I use the ternary operator. I don't think it is as confusing as some people do but I do think that one should limit how much they use it.
Most of the tortured ternaries (how's that for alliteration?) I see are merely attempts at putting logic that really belongs in an if statement in a place where an if statement doesn't belong or can't go.
For instance:
if (inVar1 != 0)
v.push_back(inVar1);
if (inVar2 != 0)
v.push_back(inVar2);
works assuming that v.push_back is void, but what if it's returning a value that needs to get passed to another function? In that case, it would have to look something like this:
SomeType st;
if (inVar1 != 0)
st = v.push_back(inVar1);
else if (inVar2 != 0)
st = v.push_back(inVar2);
SomeFunc(st);
But that's more to digest for such a simple piece of code. My solution: define another function.
SomeType GetST(V v, int inVar1, int inVar2){
if (inVar1 != 0)
return v.push_back(inVar1);
if (inVar2 != 0)
return v.push_back(inVar2);
}
//elsewhere
SomeFunc(GetST(V v, inVar1, inVar2));
At any rate, the point is this: if you have some logic that's too tortured for a ternary but will clutter up your code if it's put in an if statement, put it somewhere else!
inVar1 != 0 || v.push_back(inVar1);
inVar2 != 0 || v.push_back(inVar2);
common pattern found in languages like Perl.
If you have multiple method invocations in one or both of the tenary arguments then its wrong. All lines of code regardless of what statement should be short and simple, ideally not compounded.
A proper if statement is more readable, as others have mentioned. Also, when you're stepping through your code with a debugger, you won't be able to readily see which branch of an if is taken when everything is in one line or you're using a ternary expression:
if (cond) doIt();
cond ? noop() : doIt();
Whereas the following is much nicer to step through (whether you have the braces or not):
if (cond) {
doIt();
}
As mentioned, it's not shorter or clearer than a 1 line if statement. However, it's also no longer - and isn't really that hard to grok. If you know the ternary operator, it's pretty obvious what's happening.
After all, I don't think anyone would have a problem if it was being assigned to a variable (even if it was mutating state as well):
var2 = inVar1 == 0 ? NULL : v.push_back(inVar1);
The fact that the ternary operator always returns a value - IMO - is irrelevant. There's certainly no requirement that you use all return values...after all, an assignment returns a value.
That being said, I'd replace it with an if statement if I ran across it with a NULL branch.
But, if it replaced a 3 line if statement:
if (inVar == 0) {
v.doThingOne(1);
} else {
v.doThingTwo(2);
}
with:
invar1 == 0 ? v.doThingOne(1) : v.doThingTwo(2);
I might leave it...depending on my mood. ;)
What is the best was to evaluate an expression like the following:
(A And B) Or (A And C) Or (Not B And C)
or
(A && B) || (A && C) || (!B && C)
At runtime, I was planning on converting the above expressions to the following:
(True And False) Or (True And False) Or (Not False And True)
or
(True && False) || (True && False) || (! False && True)
Conditions:
1) The logical expression is not known until runtime.
2) The number variable and their values are not known until runtime.
3) Variable values are never null.
I know I could create a simple assemble with a class and a method that I generate at runtime based on the inputs, but is there a better way.
I have done this before. Use a string builder to write the code, then call the compiler. After that, you load the assembly and call the method.
Suggestions?
Thanks.
If you're using .NET3.5 then you can parse the text and create an abstract sytax tree using the Expression classes. Then create a suitable LambdaExpression instance and compile it into a delegate, which you can then execute.
Constructing a parser and syntax tree builder for this kind of fairly simple grammer is quite an interesting exercise, and will execute somewhat faster than invoking the compiler (and it's neater in my view as well).
If you're not using .NET3.5, then it's also not complicated to implement an interpreted abstract syntax tree yourself.
Be warned: the two final conditions you're talking about are not necessarily equivalent. The && operators in C# will use short-circuit evalution, while the logical And operator in VB does not. If you want to be sure the statements are equivalent, translate a user And to AndAlso and a user Or to OrElse.
For simple expresssions you probably won't notice a difference. But if the conditions can have side effects or if the performance difference between the two is a concern, this can be important.
You can use https://github.com/mrazekv/logicalparser
Its simply library to write logical expression (evaulated with precenednce table, allows to OR, NOT, AND operator and >, >=, <=, < on integer variables and = on string variables)
You can do this easily with:
a parser generator (like ANTLR, mentioned above) that takes boolean expressions as input and produces an infix list and
code to evaluate a Reverse Polish Notation stack.
The grammar looks something like this:
program: exprList ;
exprList: expr { Append($1); }
| expr OR exprList { Append(OR); }
| expr AND exprList { Append(AND); }
| NOT exprList { Append(NOT); }
| ( exprList ) { /* Do nothing */ }
;
expr: var { Append($1); }
| TRUE { Append(True); }
| FALSE { Append(False); }
;
To evaluate, you do this:
for each item in list
if item is symbol or truth value, push onto RPN stack
else if item is AND, push (pop() AND pop())
else if item is OR, push (pop() OR pop())
else if item is NOT, push (NOT pop())
result = pop()
For symbols, you have to substitute the truth value at runtime.
You can write a simple interpreter/parser. Use something like ANTLR and reuse existing grammars.
If you are using .NET 3.5, you can create a Lambda Expression. Then you can create a delegate from it and call as standard delegate/method.
On the internet is a lot of samples about Lambda Expressions.
One solution would be to assemble the expression as a string, and then send it SQL Server, or whatever your database is for evaluation. Replace the actual variables with 1=1 or 0=1 for True and False respectively, and you would end up with a query like this:
SELECT 1 WHERE (1=1 And 0=1) Or (1=1 And 1=1) Or (Not 0=1 And 1=1)
Then when you run the query, you get a 1 back when the result is true. May not be the most elegant solution, but it will work. A lot of people will probably advise against this, but I'm just going to throw it out there as a possible solution anyway.
This will not be the best answer, but I myself had this problem some time ago.
Here is my old code:
VB.Net - no warranty at all!
https://cloud.downfight.de/index.php/s/w92i9Qq1Ia216XB
Dim BoolTermParseObjekt As New BoolTermParse
MsgBox(BoolTermParseObjekt.parseTerm("1 und (((0 oder 1 und (0 oder 4))) oder 2)").ToString)
This code eats a String with multiple '(', ')', 'and', 'or' plus 'other things' and breaks down the logic to a boolean by replacing the things with boolean values.
therefore:
Whatever 'other things' I wanted to evaluate I had to put in Function resolveTerm()
at the comment "'funktionen ausführen und zurückgeben, einzelwert!"
in page 2.
There the only evaluation rightnow is "If number is > 1"
Greetings
Take a look at my library, Proviant. It's a .NET Standard library using the Shunting Yard algorithm to evaluate boolean expressions.
It could also generate a truth-table for your expressions.
You could also implement your own grammar.