Try this Out Guys --
int a = 20;
a++; //21
a += a--; //21+21 what about --?
a++; //21
a += a--; //21+21 what about --?
Console.WriteLine(a);
why the output is 42? why not 41 ?
why the output is 42? why not 41 ?
This is because these are postfix operations, so they are going to output the value of the variable prior to your increment or decrement statements.
As per the MSDN documentation :
The ++ and -- operators also support postfix notation, (Section 7.5.9). The result of x++ or x-- is the value of x before the operation, whereas the result of ++x or --x is the value of x after the operation. In either case, x itself has the same value after the operation.
You can see a working example demonstrating this below :
//Declare your integer value
int a = 20;
int a = 20;
//Increment it
Console.WriteLine(a++);
Console.WriteLine(a++);
//Now you'll see that your value is 21
Console.WriteLine(a);
Console.WriteLine(a);
//The following line is going to output (21) + (21)
Console.WriteLine(a += a--);
Example
If you really wanted to output 41, you would need to use postfix notation instead which would output the value after your increment or decrement operation occurred by changing this line :
Console.WriteLine(a += a--);
Example
If you really wanted to output 41, you would need to use postfix notation instead which would output the value after your increment or decrement operation occurred by changing this line :
a += a--;
to this :
to this :
a += --a;
No comments:
Post a Comment