What is the difference between these unary operators in C#?
What would an example be? What is the name of each?
+= vs. =+
++x vs. x++
They differ in how they change the value and how they return the result.
The first two += and =+ behave in the way that the first increments a variable, the other sets a variable. They are not related. Observe the following code:
// +=
x = 1;
printf( x += 1 ); // outputs 2, the same as x = x+1
printf( x ); // outputs 2
// =+
x = 1;
printf( x =+ 1 ); // outputs 1, the same as x = 1;
printf( x ); // outputs 1
The next two, ++x and x++, differ in the order their function. ++x will increment your variable by 1 and return the result. x++ will return the result and increment by 1.
// ++x
x = 1;
printf( ++x ); // outputs 2, the same as x = x+1
printf( x ); // outputs 2
// x++
x = 1;
printf( x++ ); // outputs 1
printf( x ); // outputs 2
They are mostly useful for for loops and while loops.
In terms of speed, ++x is considered a lot faster than x++ since x++ needs to create an internal temporary variable to store the value, increment the main variable, but return the temporary variable, basically more operations are used. I learned this a looong time ago, I don't know if it still applies
Let's visualize the first ones, += and =+.
Because "+" is action, "=" is assignment, so
+= is to add BEFORE assignment
=+ is a bit confusing with "+", it could be "-", for example a=+7 or a=-7, anyway, it's a direct assignment.
Similarly,
++x is "increment then return"
x++ is "return then increase"
++x vs x++ are unary operators. ++x means pre increment and x++ means post increment.
int temp;
temp = 1;
Console.WriteLine(++temp); // Outputs 2
temp = 1;
Console.WriteLine(temp++); // outputs 1
Console.WriteLine(temp); // outputs 2
Prefix increment means:
The result of the operation is the value of the operand after it has
been incremented.
Postfix increment means:
The result of the operation is the value of the operand before it has
been incremented.
Now the following:
+= means temp += 10; // same as temp = temp + 10;
This =+ isn't a valid operator.
If one does this:
str = + str; // will throw an error.
int a;
a = +2; // sort of meaningless . 2 and +2 means same.
More here: Is there such thing as a "=+" operator?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/increment-operator
Related
We know that these two addition statements are equivalent and compile to the same IL code:
int x = 100;
x += 100;
x = x + 100;
However, when there is an explicit cast required I have noticed something strange:
byte b = 100;
b += 200; // Compiles (1)
b = b + 200; // Cannot implicitly convert int to byte (2)
b = (byte) (b + 200); // Compiles (3)
It is obvious why the second statement requires an explicit cast because the result of the addition is an integer. But the weird thing to me is the first statement. It compiles to the exact same IL as the third statement, so it looks like compiler adds a cast that is supposed to be explicit, for us. But it can't do it in the second statement.
It seems contradictory to me because I would expect the first statement to be equivalent to the second and never compile, so why does it compile?
Note: This doesn't compile when an explicit cast is required from long to int:
int x = 100;
long y = 200;
x += y;
You really need to go to the specs for this sort of information (and it can be really hard to get your head around the wording). However, straight from the horses mouth
12.18.3 Compound assignment
An operation of the form x op= y is processed by applying binary
operator overload resolution (§12.4.5) as if the operation was written
x op y. Then,
If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x
op y, except that x is evaluated only once.
Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the
type of x , and if y is implicitly convertible to the type of x
or the operator is a shift operator, then the operation is evaluated
as x = (T)(x op y), where T is the type of x, except that x is
evaluated only once.
Otherwise, the compound assignment is invalid, and a binding-time error occurs.
...
blah blah blah
...
The second rule above permits x op= y to be evaluated as x = (T)(x op y) in certain contexts. The rule exists such that the predefined operators can be used as compound operators when the left operand is
of type sbyte, byte, short, ushort, or char. Even when both
arguments are of one of those types, the predefined operators produce
a result of type int, as described in §12.4.7.3. Thus, without a cast
it would not be possible to assign the result to the left operand.
The intuitive effect of the rule for predefined operators is simply
that x op= y is permitted if both of x op y and x = y are
permitted.
byte b = 0;
char ch = '\0';
int i = 0;
b += 1; // Ok
b += 1000; // Error, b = 1000 not permitted
b += i; // Error, b = i not permitted
b += (byte)i; // Ok
ch += 1; // Error, ch = 1 not permitted
ch += (char)1; // Ok
the intuitive reason for each error is that a corresponding simple
assignment would also have been an error.
In short, computer says no.
While I´m trying to understand a C# codeblock, I´m asking myself what does this code means:
y -= y > 9 ? 9:0;
Thanks in advance
Yes this bit of code is a bit confusing.
Basically the logic reads like this:
if y is greater than 9
subtract y by 9
otherwise
subtract y by 0
This is also equivalent to the following code:
if (y > 9) {
y = y - 9;
}
else {
y = y - 0;
}
The else case is of course superfluous in this case but I did a literal translation.
For further reading, you can check here. Good luck!
First evaluation:
(y > 9)
If this is true, the expression is evaluated to 9.
If this is false it is evaluated to 0.
This evaluated result is then subtracted from the current value of y.
if y > 9 then subtract 9 from y else subtract zero (do nothing).
It is here as I suppose:
if(y>9)
y=y-9;
else
y=y-0;
This makes use of the ? operator in C#. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression and evaluates as :
if(y>9)
y-= 9;
else
y-= 0;
-= is a subtraction operator.
y -= (expression) means subtract (expression) from y and store that value in y
? : is the ternary operator. It is a way to write an expression that has a conditional value.
(expression) ? x : y means evaluates to x if (expression) is true, and it evaluates to y if (expression) is false
y -= something;
means
y = y - something;
"?" is a ternary operator. Its syntax is:
condition ? true_expression : false_expression
So, the equivalent of that line is:
if (y > 9)
y = y - 9;
else
y = y - 0; // Of course, this wouldn't make sense written like this.
A clear and concise version of that line could be:
if (y > 9)
y -= 9;
I wanted to figure out a way to make my floating points move and change faster than the typical x++ so I decided to add more of those increments into the same while loop so they stack
While (True)
{
x++;
x++;
x++;
x++;
}
The functionality works but how do i do this with shorter code?
You can replace that with:
while (...)
{
x += 4;
}
This represents x = x + 4
You can also do this with subtraction, multiplication, and division, respectively -=, *=, and /=. Read more here
x += 4; // Adds 4 to x, and stores the result in x.
Try += operator:
x+=4;
in this way x will be incremented by 4.
I get very confused at times with the shorthand increment operation.
Since when i was little programming in BASIC, i got some how stuck with a = a+1 which is long painful way of saying 'Get a's current value, add 1 to it and then store the new value back to a'.
1] a = a +1 ;
2] a++ ;
3] ++a;
4] a +=1;
[1] and [4] are similar in functionality different in notation, right?
2] and 3] work simply differently because of the fact that the increment signs ++ is before and after. Right?
Am I safe to assume the below?
int f(int x){ return x * x;}
y = f(x++) -> for x =2, f(x) = x^2
f(x) ======> y= 2^2 =4
x=x+1; ======> x= 2+1 = 3
y = f(++x) -> for x =2, f(x) = x^2
x=x+1 ===========> x = 2+1 = 3
f(x) ===========> y =3^2 = 9
Difference is, what the operator returns:
The post-increment operator "a plus plus" adds one, and returns the old value:
int a = 1;
int b = a++;
// now a is 2, b is 1
The pre-increment operator "plus plus a" adds one, and returns the new value:
a = 1;
b = ++a;
// now a is 2 and b is 2
First off, you should read this answer very carefully:
What is the difference between i++ and ++i?
And read this blog post very carefully:
http://blogs.msdn.com/b/ericlippert/archive/2011/03/29/compound-assignment-part-one.aspx
Note that part two of that post was an April Fool's joke, so don't believe anything it says. Part one is serious.
Those should answer your questions.
When you have just an ordinary local variable, the statements x++; ++x; x = x + 1; x += 1; are all basically the same thing. But as soon as you stray from ordinary local variables, things get more complicated. Those operations have subtleties to them.
1], 3] and 4] are functionally identical - a is incremented by one, and the value of the whole expression is the new value of a.
2] is different from the others. It also increments a, but the value of the expression is the previous value of a.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C#: what is the difference between i++ and ++i?
I see this operator (++) very often. I know what it does ultimately, but it seems like there's some rules I don't understand. For example, it seems to matter if you put it before or after the variable you're using it on. Can someone explain this?
The statement
x++;
is exactly equivalent to
x = x + 1;
except that x is evaluated only once (which makes a difference if it is an expression involving property getters).
The difference between the following two:
DoSomething(x++); // notice x first, then ++
DoSomething(++x); // notice ++ first, then x
Is that in the first one, the method DoSomething will see the previous value of x before it was incremented. In the second one, it will see the new (incremented) value.
For more information, see C# Operators on MSDN.
It is possible to declare a custom ++ operator for your own classes, in which case the operator can do something different. If you want to define your own ++ operator, see Operator Overloading Tutorial on MSDN.
http://msdn.microsoft.com/en-us/library/36x43w8w(v=VS.80).aspx
The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand:
The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
If you put the ++ operator before the variable, it is incremented first.
If you put the ++ operator after the variable, it is incremented after.
For example(C#):
int x = 0;
Console.WriteLine("x is {0}", x++); // Prints x is 0
int y = 0;
Console.WriteLine("y is {0}", ++y); // Prints y is 1
Hope this cleared it up.
well if you put it like
variable++
It first uses the variable and the increments it (+1)
On the otherhand if you
++variable
It first increments the variable and then uses it
Another way to see it... here are two functions that do the same as prefix/postfix ++. This illustrates that prefix is, in theory, faster, because no temporary variable is needed to store the "previous" value:
// same as x ++;
int PostfixIncrement(ref int x)
{
int y = x;
x = x + 1;
return y;
}
// same as ++ x;
int PrefixIncrement(ref int x)
{
x = x + 1;
return x;
}
If you put the ++ operator before the variable, it is incremented first. If you put the ++ operator after the variable, it is incremented after.
For example(C#):
int x = 0;
Console.WriteLine("x is {0}", x++); // Prints x is 0
int y = 0;
Console.WriteLine("y is {0}", ++y); // Prints y is 1