-
February 4th, 2017, 12:36 AM
#1
[RESOLVED] Trying to understand the error in this code example
This code snippet shows the difference between the postfix and prefix versions of the increment operator. I got it out of a Schildt book. I realize many don't like the guy but I do like his style and books and I don't follow everything he does so now that I got that out of the way here is the problem:
class TrickyPostfixAndPrefix
{
static void Main()
{
int x = 10;
int y = 2;
int z;
z = x++ - (x * y);
Console.WriteLine("The first example yields " + z);
z = ++x - (x * y);
Console.WriteLine("The second example yields " + z);
Console.ReadKey();
}
When I run the code it gives the answer -12 both times. When in fact the correct answers are -12 the first time and -11 the second.
I've been looking into this and I thought that when I write z = ++x - (x * y) the second time that it would simply overwrite whatever previous value was in variable z (-12).
But that's not what's goin' on so I'm trying to figure out what C# is actually doing here.
Am I correct in thinking that the previous value of variable z which is -12 is still in that variable (it's not being overwritten) and for whatever reason which I'm not sure here but that expression z = ++x - (x * y) still ends up assigning -12 to variable z again?
If you run the code you will see...
Been many years since I programmed and I only do it for fun.
-
February 4th, 2017, 12:47 AM
#2
Re: Trying to understand the error in this code example
Oh, I figured it out. In order to make the code produce the correct result I needed to reset variable x back to 10 before I wrote the second prefix expression.
Runs good now.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|