This question already has answers here:
What is the difference between i++ and ++i?
(7 answers)
Closed 3 years ago.
I dont understand why the value of i and k is still 5 in line number 19 ,20,after post increment?
The value of i is still 5 though after post increment.
`using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Increment
{
class Program
{
static void Main(string[] args)
{
int i = 5;
int j = 10;
Console.WriteLine("before incrementing{0}",i);
i=i++;
Console.WriteLine("after incrementing {0}",i); //i=5?
int k = i;
Console.WriteLine("after incrementing i and assign {0}", k);//K=5?
}
}
}`
Imagine post-increment and pre-increment as functions:
int PreIncrement(ref int i)
{
i = i + 1;
return i;
}
int PostIncrement(ref int i)
{
int valueBefore = i;
i = i + 1;
return valueBefore;
}
In this case
i = i++;
would be the equivalent of
i = PostIncrement(ref i);
You are performing two actions, in this order:
Incrementing i
Setting i to equal the value it equalled before it was incremented
The documentation for ++ has reasonably clear examples. "The result of x++ is the value of x before the operation, as the following example shows... ."
That means however you use x++ in an expression you will be getting the initial value, i.e. prior to x being incremented. So if x is 4 then the value 4 will be used in the expression and x will be incremented to 5. If the expression's value is assigned to a variable then the variable is set to 4. You happen to have chosen x as the target of the assignment, thus overwriting the post-incremented value.
Related
This is my test code,it's very simple:
class Program
{
static void Main(string[] args)
{
int number = 0;
int newNumber = number++;
Console.WriteLine("the old number is {0},the new number is:{1}", number, newNumber);
Console.Read();
}
}
whereas the output result is:'the old number is 1,the new number is:0',I think it's opposite with the result I want.
using the postfix increment ++ operator, it first returns the original value, then increments. To get what you want use the prefix increment operator like
int newNumber = ++number;
But if you don't want to change number, don't use an incrementing operator, use addition/subtraction instead.
That is because number++ updates the value of number by incrementing it (PostFix). This is done after using the original value in the expression it is used. To achieve the desired behaviour, You can use:
int number = 0;
int newNumber = number + 1;
Here, you have used number++ which is Post increment operator.
It assigns the value first and then increments its value.
You can achieve your desired output in two ways :
Use Pre increment operator
int newNumber = ++number;
Simply adding 1 to number variable and then assigning it to newNumber
int newNumber = number + 1;
This question already has answers here:
What does "Use of unassigned local variable" mean? [duplicate]
(11 answers)
Closed 3 years ago.
I am new to C#, my last programming language was C
I kept getting Use of unassigned local variable 'average'
The average it is pertaining was the average /= 10;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int i, average;
int[] scores = new int[10];
Console.WriteLine("Enter 10 scores");
for (i = 0; i < 10; i++)
{
scores[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 10; i++)
{
average = scores[i] + scores[i + 1];
i++;
}
average /= 10;
Console.WriteLine("Average of All the Scores: {0}", average);
Console.Read();
}
}
}
When you declare the variable 'average', set it to 0.
Here's a fixed version of your code, with comments as to why I made the change:
class Program
{
static void Main(string[] args)
{
//fix the 'use of undefined' error
int average = 0;
int[] scores = new int[10];
Console.WriteLine("Enter 10 scores");
//it's better to scope loop iteration variables to the loop unless you specifically need them outside
for (int i = 0; i < 10; i++)
{
scores[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < 10; i++)
{
//your old code would crash here, and had the wrong algorithm for calculating an average; it didn't sum all the entered values, just the last two
average += scores[i];
}
average /= 10;
Console.WriteLine("Average of All the Scores: {0}", average);
Console.Read();
}
}
I was puzzled as to why the error occurred too because the second loop was clearly assigning a value and I knew that inner scopes could set values and the compiler would recognise them.. learning day for me too as I was formerly unaware that some loops are excluded even when they're set up so they look like they will definitely run. In simple terms it seems that when a loop is set up so that its running is conditional on a variable, the flow analysis considers that in some scenarios the loop might not run even though it's clear to the human reading the code that the loop will always run. Consider these:
//this is fine, flow analysis determines this loop will always run
int average;
while(true){
average = 0;
break;
}
average /= 10;
//this raises the same error even though we as a human can definitely see this loop will always run
int average;
int w = 0;
while(w<1){
average = 0;
}
average /= 10;
Making the loop conditional on a variable meant the compiler wa and longer sure the variable was assigned
As another more involved example, you could also fix your error with this bizarre construct as your first loop:
for (int i = 0; true; i++)
{
average = 0;
scores[i] = Convert.ToInt32(Console.ReadLine());
if(i >= 10)
break;
}
Again the compiler can be sure this loop will always run and your variable will be assigned
here's Peter's comment in case the other answer/the comment goes away:
the compiler doesn't implement any static flow analysis that would confirm that the average variable is set. According to the "definite assignment" rules of C#, loops are ignored because it's possible for a loop to not iterate even once. Thus, average is not definitely assigned, and thus the error. See marked duplicate, and of course the C# language specification, for more details.
The code
public static void InitializeArray(ref double[] doubleA)
{
//array init using foreach
int i = 0;
foreach (double dub in doubleA)
{
doubleA[i++] = i + .5;
}
}
is giving me an output of
doubleA[0] = 1.5 instead of .5
doubleA[1] = 2.5 instead of 1.5
and so on
I'm not understanding why it's doing that. As I understand it, doubleA[0] should be getting 0.5 because I'm only adding 0.5 so where is the extra 1 coming from? I'm thinking it's from int i but for i=0, shouldn't it evaluate to doubleA[0] = 0 + .5?
So far I have tried writing doubleA[i++] = i + .5; instead which gives each element in the array just the value of 0.5.
So let's start with i = 0
doubleA[i++] = i + .5;
Here you are accessing position 0 of the array, but also adding 1 to the value of i. When i == 0, the expression i++ will be the value 0, but the value of the variable i is incremented such that the new value of i is 1.
On the right hand side, this new value of i is used (1) and added to 0.5. Giving a value of 1.5 which is assigned back to index 0 of the array (as indicated on the left hand side of the assignment).
I could go on, but I think you probably get it by now...
Further reading on operator ++
This is because i is being incremented in your key: doubleA[i++]. i++ will increment the key by one, AFTER returning it. When it's used later (as the value), its value has already been incremented. So now you're setting it to 1 + 0.5.
Let's break this down, and show you the functional equivalent, and you'll see exactly what this is happening:
public static void InitializeArray(ref double[] doubleA)
{
//array init using foreach
int i = 0;
foreach (double dub in doubleA)
{
int key = i;
i = i + 1;
doubleA[key] = i + .5;
}
}
This question already has answers here:
Post-increment within a self-assignment
(6 answers)
Closed 5 years ago.
Here's a simple console application code, which returns a result I do not understand completely.
Try to think whether it outputs 0, 1 or 2 in console:
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int i = 0;
i += Increment(ref i);
Console.WriteLine(i);
Console.ReadLine();
}
static private int Increment(ref int i)
{
return i++;
}
}
}
The answer is 0.
What I don't understand is why post increment i++, from the Increment method, which is executed on a ref (not on a copy of the passed variable) does increment the variable, but it just gets ignored later.
What I mean is in this video:
Can somebody explain this example and why during debug I see that value is incremented to 1, but then it goes back to 0?
i += Increment(ref i); is equivalent to
i = i + Increment(ref i);
The expression on the right hand side of the assignment is evaluated from left to right, so the next step is
i = 0 + Increment(ref i);
return i++ returns the current value of i (which is 0), then increments i
i = 0 + 0;
Before the assignment the value of i is 1 (incremented in the Increment method), but the assignment makes it 0 again.
i think the "magic" here is just operation precedence the order of operations
i += Increment(ref i)
is the same as
i = i + Increment(ref i)
the + operation is executed left to right
so first we take i ... wich is 0 at that time ...
then we add the result of Increment(ref i) ... which is also 0 ... 0+0=0 ... but wait ... before we get that result i is actually incremented ...
that increment takes place after the left operand of our + operation has ben evaluated ... so it does not change a thing ... 0+0 still is 0 ... thus i is assigned 0 after the + operation has been executed
As you mentioned - postincrement "i++". statement - "return i++;" will set the value of 'i' in memory after original value is returned.
try using "return ++i;" and probably you will get it.
I have a simple c# console application but i am getting wrong output why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
int i = 100;
for (int n = 0; n < 100; n++)
{
i = i++;
}
Console.WriteLine(i);
}
}
}
i++ is an expression which returns i, then increments it.
Therefore, i = i++ will evaluate i, increment i, then assign i to the original value, before it was incremented.
You need to use ++i, which will return the incremented value.
I'm guessing that you really want an explanation as to why it doesn't work as expected, rather than to actually get the result since you can get that by setting i equal to 200 in the first place.
The postincrement operator is applied after a temporary copy of the variable is created. The temporary is used for operations in the statement then the assignment is performed, thus your loop is equivalent to:
for (int n = 0; n < 100; n++)
{
j = i;
i++;
i = j;
}
Since that's the case, the increment is basically discarded and i is never actually incremented.
i = i++;
This sets i to the old value of i, then increments it. I think you want:
i++;
Or better yet if your compiler is lame and doesn't optimize the return:
++i;
Cheers.
The line i = i++; writes twice to the variable i. The post increment is executed first, but then the assignment statement overwrites it.
Try just i++;
Just use i++, not i = i++.