Thursday, December 4, 2014

An Interview Question For C# Programmers

Q: Consider following code snippet 


int i=5; 
i=i++;

Please find original post from here


after these two lines what will be the value of  i ?

 Ans: 5

illustration: -       

Please find original post from here

Most of us answer 6 but it's not the case, Value of i remains unchanged (i remains as 5). But somewhere along the execution, value of i was 6 but it is assigned with value 5 finally.

Consider the following program


class Program
{
    static int i;
    static void Main(string[] args)
    {
        i = 5;
        i = postIncrement();
    }
    static int postIncrement()
    {
        return i++;
    }
}
separate function for post Increment is written for better understanding of problem.Now While debugging the program in visual studio it will look like this
Image Showing Debugging of the problem
Debugging of the problem in VS 2012


Steps Involved:-

1. i initialised to 5.


2. i++ operator returns 5 but not assigned to i.

3. i++ operator increments value of  i  to 6.


4. i is assigned with 5 which is the value returned by i++ in step 2.


try to solve related questions like

int i=5; 
i=(i++)+i+(++i);




Please find original post from here

after thes two lines what will be the value of i? Comment you answer please.


◙ Done.Happy Coding   
»Keep Sharing and Learning«

17 comments: