Continue from
http://www.c-sharpcorner.com/Forums/Thread/220857/code-snippet-functionality.aspx
j is initialized to 1 therefore 1st operand (j++) takes the value of 1. Concurrently 2nd operand also takes the value of 1 but it as a prefix(++j) operator value 1 is quickly convert into 2. Therefore k (1+2) must be 3, but in the output k=4 how can this be explained.
using System;
namespace Code
{
class Program
{
static void Main(string[] args)
{
int i, j = 1, k;
for (i = 0; i < 5; i++)
{
k = j++ + ++j;
Console.Write(k + " ");
}
Console.ReadKey();
}
}
}
//4 8 12 16 20
Loading

VulpesRank #55 · 29.2K reputationPosted Jul 28, 2013, 12:01 PM EDT
j's memory slot receives values of:
1 - initially
2 - postfix ++
3 - ++ prefix
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 28, 2013, 4:49 AM EDT
In postfix increment, the equation is evaluated first, and then the increment operation takes place,
Regards,
Iftikar
Posted Jul 28, 2013, 5:54 AM EDT
using System;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int i, j = 1, k, m = 1;
for (i = 0; i < 5; i++)
{
k = j++ + ++m;
Console.Write(k + " ");
}
Console.ReadKey();
}
}
}
//3 5 7 9 11
VulpesRank #55 · 29.2K reputationPosted Jul 28, 2013, 6:11 AM EDT
Posted Jul 28, 2013, 11:20 AM EDT
Posted Jul 28, 2013, 4:59 PM EDT