Showing different output from my acceptation - c#

Hay I didn't know even If this question has asked before but my problem is as following.
In my c# console application I had declared a variable i with assigning a value as
int i = 0 and now I want increment i by 2, obviously I can use following cede.
int i = o;
i += 2;
Console.WriteLine(i);
Console.ReadLine();
//OUTPUT WILL BE 2
but this one is my alternate solution. As my lazy behavior I refuse to use this code and I had used following code.
int i = 0;
i += i++;
Console.WriteLine(i);
Console.ReadLine();
In above code I had accepted FIRST i++ will increment by one and than after it will again increment by i+=i but this thing is not happen.!!!
I doesn't know why this thing is happening may be I had done something wrong or some compilation problem.?????
Can any one suggest me why this happening????
I just want to know why code no 2 is not working? what is happening in there?

The i++ returns the value of i (0) and then adds 1. i++ is called post-increment.
What you are after is ++i, which will first increase by one and then return the increased number.
(see http://msdn.microsoft.com/en-us/library/aa691363(v=vs.71).aspx for details about increment operators)

i needs to start off with 1 to make this work.
int i = 1;
EDIT::
int i = 0;
i += i++;
Your code above expresses the following:
i + 0 then add one
if you use i += ++i; then you'll get i + 1 as it processed the increment beforehand.

What your code is doing:
"i++" is evaluated. The value of "i++" is the value of i before the increment happens.
As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1;
The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0.
That is, "i = i++" roughly translates to
int oldValue = i;
i = i + 1
//is the same thing as
i = oldValue;
The post-increment operator increments the value of your integer "i" after the execution of your i++
For your information:
i++ will increment the value of i, but return the pre-incremented value.
++i will increment the value of i, and then return the incremented value.
so the best way of doing the 2 step increment is like that:
i +=2

Related

I don't understand how 'i' become 4 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
how does the optput come as
3
3
4
I don't understand how 'i' become 4 for last
code:
int i = 2;
Console.WriteLine(++i);
Console.WriteLine(i++);
Console.WriteLine(i);
Because you first used the prefix increment operator and then used postfix.
int i = 2;
Console.WriteLine(++i); // i became 3 *before it was used*
Console.WriteLine(i++); // i first used, still 3, and then incremented becoming 4
Console.WriteLine(i); // i is still 4
In c# assigning a value to a variable also returns a value. Usually it is the value that is assigned
Here is an assignment, the current time is assigned to the now variable:
DateTime now = DateTime.Now;
This assignment also results in a returned value of the current time. It means you can legally write this:
DateTime now;
Console.WriteLine(now = DateTime.Now);
Not only will your now variable end up set to the current time, but the value of what was assigned is printed out, so the current time is printed
This is also an assignment:
int i = 2;
And so is this:
++i;
It is short for this:
i = i + 1;
Now because we know assignments return values we know it's legal to print out assignments:
Console.WriteLine(i = i + 1);
If i was 2, the sum on the right would be evaluated to give 3, then 3 would be assigned into i, and then also 3 is returned so 3 prints out in the console
i++ is more like a special case, where the value that i was BEFORE the assignment is made, is printed out. You can think of i++ as working like:
int i_before = i; //remember it
i = i + 1;
return i_before; //return the old value
So this:
Console.WriteLine(i++);
If i is 3 already, it will be incremented to 4, but 3 is returned and printed
The easy way to remember the difference between i++ and ++i is:
"in i++ the i is before the ++ so the value you get returned is what i was before it was incremented"
If you just use the increment as a statement on its own, it makes no difference which you use:
int i = 2;
i++;
++i;
Console.WriteLine(i); //4
It only matters which you use if you are relying on the "assignment returns a value" behavior
By the time the last line of your code comes around, i is 4 because it has been incremented twice, from 2
i starts out as 2.
On the first line, you (pre) increment it to 3, and then print it out.
On the second line, you print it out and then increment it (post increment), so it's now 4.
On the last line, you just print out the current value, which is 4, as noted above.

How to increase value of an integer higher than 1 in one command?

You could write example++; multiple times in your loop if you need to increase by more than 1, but what if i need to increase by like 100? Is there a way to make it multiply or increase by more than 1? (other than multiplying it in Console.WriteLine)
Per the comment from peter:
example += 100;
Means the same as
example = example + 100;
This is called Compound Assignment and there are many operators that do their work in this way, such as
example -= 100;
example *= 100;
For the full list, refer to the MSDN linked above
Any assignment in c# returns the assigned value so it can be used as part of a bigger statement. The += is no different, and this will print "x incremented is 101":
int x = 1;
Console.WriteLine("x incremented is " + (x+= 100));
The only thing worthy of note is that ++ exists in two forms, either x++ or ++x - the first form returns the value of x before it was incremented, the second form returns the value after.
int x = 1;
Console.WriteLine("x incremented is " + (x++)); //x is now 2 but the message says it is 1
Console.WriteLine("x incremented is " + (++x)); //x is now 3 and the message says it is 3
+= only returns the value after increment. There is no form that returns x before you add 100 to it
The simplest solution to increase value of example by an amount x would be example=example+x. This is more legible, however you can use the short form example+=x.

Expanding pre increment operator in programming languages [duplicate]

This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 9 years ago.
For example, i++ can be written as i=i+1.
Similarly, how can ++i be written in the form as shown above for i++?
Is it the same way as of i++ or if not please specify the right way to write ++i in the form as shown above for i++?
You actually have it the wrong way around:
i=i+1 is closer to ++i than to i++
The reason for this is that it anyway only makes a difference with surrounding expressions, like:
j=++i gives j the same value as j=(i+=1) and j=(i=i+1)
There's a whole lot more to the story though:
1) To be on the same ground, let's look at the difference of pre-increment and post-increment:
j=i++ vs j=++i
The first one is post-increment (value is returned and "post"=afterwards incremented), the later one is pre-increment (value is "pre"=before incremented, and then returned)
So, (multi statement) equivalents would be:
j=i; i=i+1; and i=i+1; j=i; respectively
This makes the whole thing very interesting with (theoretical) expressions like j=++i++ (which are illegal in standard C though, as you may not change one variable in a single statement multiple times)
It's also interesting with regards to memory fences, as modern processors can do so called out of order execution, which means, you might code in a specific order, and it might be executed in a totally different order (though, there are certain rules to this of course). Compilers may also reorder your code, so the 2 statements actually end up being the same at the end.
-
2) Depending on your compiler, the expressions will most likely be really the same after compilation/optimization etc.
If you have a standalone expression of i++; and ++i; the compiler will most likely transform it to the intermediate 'ADD' asm command. You can try it yourself with most compilers, e.g. with gcc it's -s to get the intermediate asm output.
Also, for many years now, compilers tend to optimize the very common construct of
for (int i = 0; i < whatever; i++)
as directly translating i++ in this case would spoil an additional register (and possible lead to register spilling) and lead to unneeded instructions (we're talking about stuff here, which is so minor, that it really won't matter unless the loop runs trillion of times with a single asm instruction or the like)
-
3) Back to your original question, the whole thing is a precedence question, as the 2 statements can be expressed as (this time a bit more exact than the upper explanation):
something = i++ => temp = i; i = i + 1; something = temp
and
something = ++i => i = i + 1; something = i
( here you can also see why the first variant would theoretically lead to more register spilled and more instructions )
As you can see here, the first expression can not easily be altered in a way I think would satisfy your question, as it's not possible to express it using precedence symbols, e.g. parentheses, or, simpler to understand, a block). For the second one though, that's easy:
++i => (++i) => { i = i + 1; return i } (pseudo code)
for the first one that would be
i++ => { return i; i = i + 1 } (pseudo code again)
As you can see, this won't work.
Hope I helped you clear up your question, if anything may need clarification or I made an error, feel free to point it out.
Technically j = ++i is the same as
j = (i = i + 1);
and j = i++; is the same as
j = i;
i = i + 1;
You can avoid writing this as two lines with this trick, though ++ doesn't do this.
j = (i = i + 1) - 1;
++i and i++ both have identical results if written as a stand alone statement (as opposed to chaining it with other operations.
That result is also identical to i += 1 and to i = i + 1.
The difference only comes in if you start using the ++i and i++ inside a larger expression.
The real meaning of this pre and post increment, you 'll know only about where you are using that.?
Main difference is
pre condition will increment first before execute any statement.
Post condition will increment after the statement executed.
Here I've mention a simple example to you.
void main()
{
int i=0, value;
value=i++; // Here I've used post increment. Here value of i will be assigned first then It'll be incremented.
// After this statement, now Value will hold the value 0 and i will hold the value 1
// Now I'm going to use pre increment
value=++i; // Here i've used pre increment. So i will be incremented first then value will be assigned to value.
// After this statement, Now value will hold the value 2 and i will hold the value 2
}
This may be done using anonymous methods:
int i = 5;
int j = i++;
is equivalent to:
int i = 5;
int j = new Func<int>(() => { int temp = i; i = i + 1; return temp; })();
However, it would make more sense if it were expanded as a named method with a ref parameter (which mimics the underlying implementation of the i++ operator):
static void Main(string[] args)
{
int i = 5;
int j = PostIncrement(ref i);
}
static int PostIncrement(ref int x)
{
int temp = x;
x = x + 1;
return temp;
}
There is no 'equivalent' for i++.
In i++ the value for i is incremented after the surrounding expression has been evaluated.
In ++i and i+1 the value for i is incremented before the surrounding expression is evaluated.
++i will increment the value of 'i', and then return the incremented value.
Example:
int i=1;
System.out.print(++i);
//2
System.out.print(i);
//2
i++ will increment the value of 'i', but return the original value that 'i' held before being incremented.
int i=1;
System.out.print(i++);
//1
System.out.print(i);
//2

How and where do i use the i++ operator in C#?

I was wondering if anyone could tell me about the i++ operator in C#.
I know it adds one to the int value, but I wouldn't have a clue where to use it, and if its only for loop statements, or can be used in general projects.
If I could get some practical examples of where you might use the i++ operator, thank you.
This is post-increment,which means that the increment will be done after the execution of the statement
int i=0;
Console.Write(i++); // still 0
Console.Write(i); // prints 1, it is incremented
In general, given this declaration:
var myNum = 0;
anywhere you would normally do this:
myNum += 1;
You could just do this:
myNum++;
What you are referring to is the C# post increment operator, common use case are :
Incrementing the counter variable in a standard for loop
Incrementing the counter variable in a while loop
Accessing an array in sequential order (3)
Example (3) :
int[] table = { 0, 1, 2, 3, 4, 5, 6 };
int i = 0;
int j = table[i++]; //Access the table array element 0
int k = table[i++]; //Access the table array element 1
int l = table[i++]; //Access the table array element 2
So, whats the post increment operator really does ?
It return the value of the variable and then increment it's value by 1 unit .
The expression i++ is just like x == y > 0 ? x : z which both are syntactic sugar.
x = i++ saves you the space of writing x=i; i=i+1;
Is it good or bad? There is really no exact answer to this.
I personally avoid these expressions as they make my code look complex, sometimes hard to debug. Always think code readability instead of write-ability, always think how your code looks readable instead of how easy is it to write it

int[] arr={0}; int value = arr[arr[0]++]; Value = 1?

Today I came a cross an article by Eric Lippert where he was trying to clear the myth between the operators precedence and the order of evaluation. At the end there were two code snippets that got me confused, here is the first snippet:
int[] arr = {0};
int value = arr[arr[0]++];
Now when I think about the value of the variable value, I simply calculate it to be one. Here's how I thought it's working.
First declare arr as an array of int
with one item inside of it; this
item's value is 0.
Second get the value of arr[0] --0 in
this case.
Third get the value of arr[the value
of step 2] (which is still 0) --gets
arr[0] again --still 0.
Fourth assign the value of step 3
(0) to the variable value. --value =
0 now
Add to the value of step 2 1 --Now
arr[0] = 1.
Apparently this is wrong. I tried to search the c# specs for some explicit statement about when the increment is actually happening, but didn't find any.
The second snippet is from a comment of Eric's blog post on the topic:
int[] data = { 11, 22, 33 };
int i = 1;
data[i++] = data[i] + 5;
Now here's how I think this program will execute --after declaring the array and assigning 1 to i. [plz bear with me]
Get data[i] --1
Add to the value of step 1 the value
5 --6
Assign to data[i] (which is still 1)
the value of step 2 --data[i] = 6
Increment i -- i = 2
According to my understanding, this array now should contain the values {11, 27, 33}. However, when I looped to print the array values I got: {11, 38, 33}. This means that the post increment happened before dereferencing the array!
How come? Isn't this post increment supposed to be post? i.e. happen after everything else. What am I missing guys?
The postincrement operation occurs as part of evaluating the overall expression. It's a side effect which occurs after the value is evaluated but before any other expressions are evaluated.
In other words, for any expression E, E++ (if legal) represents something like (pseudo-code):
T tmp = E;
E += 1;
return tmp;
That's all part of evaluating E++, before anything else is evaluated.
See section 7.5.9 of the C# 3.0 spec for more details.
Additionally, for assignment operations where the LHS is classified as a variable (as in this case), the LHS is evaluated before the RHS is evaluated.
So in your example:
int[] data = { 11, 22, 33 };
int i = 1;
data[i++] = data[i] + 5;
is equivalent to:
int[] data = { 11, 22, 33 };
int i = 1;
// Work out what the LHS is going to mean...
int index = i;
i++;
// We're going to assign to data[index], i.e. data[1]. Now i=2.
// Now evaluate the RHS
int rhs = data[i] + 5; // rhs = data[2] + 5 == 38
// Now assign:
data[index] = rhs;
The relevant bit of the specification for this is section 7.16.1 (C# 3.0 spec).
For the first snippet, the sequence is:
Declare arr as you described:
Retrieve the value of arr[0], which is 0
Increment the value of arr[0] to 1.
Retrieve the value of arr[(result of #2)] which is arr[0], which (per #3) is 1.
Store that result in value.
value = 1
For the second snippet, the evaluation is still left-to-right.
Where are we storing the result? In data[i++], which is data[1], but now i = 2
What are we adding? data[i] + 5, which is now data[2] + 5, which is 38.
The missing piece is that "post" doesn't mean "after EVERYTHING else." It just means "immediately after I retrieve the current value of that variable." A post increment happening "in the middle of" a line of code is completely normal.
data[i++] // => data[1], then i is incremented to 2
data[1] = data[2] + 5 // => 33 + 5
I would expect the post-increment operator to increment the variable after its value is used.
In this case, the variable is incremented before the second reference to the variable.
If it would not be so, you could write
data[i++] = data[i++] + data[i++] + data[i++] + 5
If it would be like you say, then you could remove the increment operator because it doesn't do actually anything, in the instruction I reported.
You have to think of assignments in three steps:
Evaluate left hand side (=get address where the value should be stored)
Evaluate right hand side
Assign the value from step 2 to the memory location from step 1.
If you have something like
A().B = C()
Then A() will run first, then C() will run, and then the property setter B will run.
Essentially, you have to think of your statement as
StoreInArray(data, i++, data[i] + 5);
The cause might be that some compilers optimize i++ to be ++i. Most of the time, the end result is the same, but it seems to me to be one of those rare occasions when the compiler is wrong.
I have no access to Visual Studio right now to confirm this, but try disabling code optimization and see if the results will stay the same.

Categories