You must Sign In to post a response.
  • Category: Career Guidance

    Difference between ++a and a++ in c#

    Hi all,

    Today I met a interview question

    what is the result for the following code in c# ?

    int a = 29;
    a--;
    a -= ++a;


    actually I checked this code in a c# function it return -1.

    So please tell me what is the logic in this code....


    Thanks in advance
  • #752380
    Hai Ramesh Kumar,
    This is correct as per the C# coding.itmight behe differently when you use C language.
    As per the C# language:

    int a = 29;
    a--;
    a -= ++a;
    Console.WriteLine(a.ToString());

    Line #1: Setting the value 29 to the integer variable so value of a will be 29.
    Line #2: a-- will have now 28(in C#) with the decrements of 1.
    Line #3:it is equivalent to
    a = a - (++a);
    So again a will be increment to 29 and then 28-29 will return -1. Which is assigned to a again.
    Line #4: Printing the value of a.
    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #752382
    Hi,

    There is very basic difference in both.
    a++ is used to get value of a variable and than it increments value of a.
    ++a is used to increment value and than get value of a.
    I hope you got my point,
    If still you have an issue ,than i'll get back to you.

    Regards,
    Nirav Prabtani (Senior Web Developer)
    Email : niravjprabtani@gmail.com
    blog : niravprabtani.blogspot.in

  • #752399
    Hi,

    In simple explanation

    a++ is called as postfix and ++a is called as prefix

    When you say a++ compiler adds 1 to a but returns the old value.

    When you say ++a compiler adds 1 to a and returns the new value


    Regards,
    Asheej T K

  • #752444
    Thanks All ..I got clear idea...


  • Sign In to post your comments