How this Actually Works

Discussion in 'C' started by ankit1703, Jan 1, 2013.

  1. ankit1703

    ankit1703 New Member

    Joined:
    Jan 1, 2013
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    int a=10,b;
    b=a++ + ++a;

    specially with a++ ?
     
  2. ankit1703

    ankit1703 New Member

    Joined:
    Jan 1, 2013
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Re: 100 Multiple choice questions in C

    int a=10,b;
    b=a++ + ++a;
    how this actually works ?
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Whatever result you see is undefined because you are using modifiers more than once on the same variable in the same statement.
     
    jupiterjones likes this.
  4. iranjit

    iranjit New Member

    Joined:
    Jan 5, 2013
    Messages:
    4
    Likes Received:
    2
    Trophy Points:
    0
    Home Page:
    http://www.programiz.com
    For prefix increment:

    Code:
    int a=10;
    printf( "%d" , ++a);
    
    The output will be 11. I am sure you understand it why?

    For postfix increment:

    Code:
    int a=10;
    printf( "%d" , a++);
    
    The output will be 10. It is because, the value of a is returned first then only it is increased by 1.

    Here is another example:

    Code:
    int a=10, b;
    printf( "%d" , a++);    // 10 is displayed
    ++a;                   // a becomes 12 after this statement
    
    In you example, it doesn't matter if you use prefix or postfix increment but there are cases when, prefix and postfix increment gives different result.
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice