C# Increment operator (++) question
Well, this is a nice one. We all familiar with incremental operators, but from what i saw yesterday… well, there is no need to give a developer some tricky assignment so he could find a way to make some bugs.
What will be the output of the next code ?
static void Main(string[] args)
{
int i = 100;
for (int n = 0; n < 100; n++)
{
i = i++;
}
Console.WriteLine(i);
}
Categories: ASP.NET, C#, Interview Questions, Programming, Teasers, Tips & Tricks


Little but Interesting Addition!
i guess output will be 200 because the for loops 100 times and
“i = i++;” can be translated to
{ i=i; i=i+1; }
ok output is 100. i always fail at your tests
@Mausi
Don’t be sad
I’ve got another one for you : LINQ Teaser
int a=5,p;
p=a++ + ++a + a++;
What will be output in C#.
In c output will be- p=18, a=8 in c++ – p=18, a=8 , in Java p=18, a=8 but in C#- p=19 , a=8 it is wront or right. If right then how can c# work on Increment / Decrement operator
@Xander
I am new to c#. Can u tell me why increment operator is not working in this case?
thanks.
@F@!S@L |Qb@L
I am new to c#. Can u tell me why increment operator is not working in this case?
thanks.
@Vinni
The result of the operation w++ is actually the value of the operand (w) itself just be for the increment (++). Since w was 100 before the operation and was assigned back to w, it will always stay 100.
This is also know as a post fix incremenet.
If you want it to be incremented and assigned use ++w;
You should try that
int a = 2;
bool c = (a = a++ + ++a – a– + –a * ++a + ++a -2) == 8;
@Yvan Dubois
i made a mistake, it should be:
bool c = ((a = a++ + ++a – a– + –a * ++a + ++a – 2) == 8);