Can someone explain the ++ operator? [duplicate] - c#

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

Related

Why is x = x + 100 treated differently than x += 100 that compiles to the same IL?

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.

Difference between unary operators ( += , =+ , ++x , and x++)

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

How to make ++ operator increments stack with shorter code?

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.

C# post increment and pre increment

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.

Why doesn't this overflow?

Given this code:
int x = 20000;
int y = 20000;
int z = 40000;
// Why is it printing WTF? Isn't 40,000 > 32,767?
if ((x + y) == z) Console.WriteLine("WTF?");
And knowing an int can hold −32,768 to +32,767. Why doesn't this cause an overflow?
In C#, the int type is mapped to the Int32 type, which is always 32-bits, signed.
Even if you use short, it still won't overflow because short + short returns an int by default. If you cast this int to short - (short)(x + y) - you'll get an overflowed value. You won't get an exception though. You can use checked behavior to get an exception:
using System;
namespace TestOverflow
{
class Program
{
static void Main(string[] args)
{
short x = 20000;
short y = 20000;
short z;
Console.WriteLine("Overflowing with default behavior...");
z = (short)(x + y);
Console.WriteLine("Okay! Value is {0}. Press any key to overflow " +
"with 'checked' keyword.", z);
Console.ReadKey(true);
z = checked((short)(x + y));
}
}
}
You can find information about checked (and unchecked) on MSDN. It basically boils down to performance, because checking for overflow is a little bit slower than ignoring it (and that's why the default behavior is usually unchecked, but I bet that in some compilers/configurations you'll get an exception on the first z assignment.)
http://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx
Type: int
Range: -2,147,483,648 to 2,147,483,647
While everyone is correct in saying that an "int" type on a 32 bit machine is most likely 2^32, there is a glaring flaw in your methodology.
Let's assume that int was 16 bit. You're assigning a value that will overflow z, so z itself is overflowed. When you calculate x+y you're also overflowing the int type, it's very likely that both cases will overflow to the same value, meaning you'd hit your equality regardless(this is probably compiler dependent, I'm not quite sure whether x+y will be promoted).
The correct way to do your experiment would be for z to have a larger data type than x and y. For example(Sorry for plain C, I'm not much of C# person. Hopefully it illustrated the methodology, however.)
int x = INT_MAX;
int y = INT_MAX;
int sum = x + y;
long long z = INT_MAX+INT_MAX;
if(sum == z)
printf("Why didn't sum overflow?!\n");
Comparing sum and z is important as comparing x+y and z may still come out fine depending on how the compiler handles promotion.
In C#, an Int is 4 bytes. So it maxes out at 2^31 or 2,147,483,648. If you want a 2 byte integer, use a short instead of an int.
Because an int in .NET is a signed 32 bit number with a range of -2,147,483,648 to 2,147,483,647.
Reference : http://msdn.microsoft.com/en-us/library/5kzh1b5w(VS.80).aspx
Because ints are 32-bit, holding values up to ±2GB.
An int's size is 4 byte so it can hold at least 2^31 which is around 2 billion.
The int keyword maps to the .NET Framework Int32 type, which can hold integers in the range from -2,147,483,648 to 2,147,483,647.
in C# int (System.Int32) is of 32 bits which can happily store this value.
you are given to print the result as "WTF?" .Then how should it display other value.
Int means int32 its range is –2147483648 to 2147483647
you are given the range of int16 :–32768 to 32767
This is the reason it is not throwing any error
First of all your code is in the range for int... However if it were not in the range then it wont complain either... coz you are never assigning a value back to any variable after doing X+Y in your if check...
Suppose if you were doing X * Y then it'll be calculated and the result would be a long value then the value from variable Z is taken and promoted to a long then both would be compared... Remember the casting from a lower range primitive to upper range primitive value is implicit.
int x = 200000; //In your code it was 20000
int y = 200000; //In your code it was 20000
int z = 40000;
// Why is it printing WTF? Isn't 40,000 > 32,767?
// Note: X + Y = 200000 and not < 32,767
// would pass compiler coz you are not assigning and values are compared as longs
// And since it's not equals to 40,000 the WTF did not got printed
if ((x + y) == z) Console.WriteLine("WTF?");
// And x * y >= z is true WTF MULTIPLY got printed
if ((x * y) >= z) Console.WriteLine("WTF MULTIPLY?");
// Compiler would fail since x can't hold 40,00,00,00,000
x = x * y;
All the above is true, however, it's important to know, that if you assign a number greater than 2^32, it will not compile!

Categories

Resources