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
VulpesPosted Jul 28, 2013, 4:01 PM
j's memory slot receives values of:
1 - initially
2 - postfix ++
3 - ++ prefix
Posted Jul 28, 2013, 8:59 PM
Posted Jul 28, 2013, 3:20 PM
VulpesPosted Jul 28, 2013, 10:11 AM
Posted Jul 28, 2013, 9:54 AM
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
Iftikar HussainPosted Jul 28, 2013, 8:49 AM
In postfix increment, the equation is evaluated first, and then the increment operation takes place,
Regards,
Iftikar