The x++ and ++x Operators
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: The x++ and ++x Operators

  1. #1
    Join Date
    Jul 2013
    Posts
    1

    The x++ and ++x Operators

    Hi, I'm newbie in programming. I hope can find answer in this forum.

    First of all, I have a program/code like this:

    int a, b

    a = 1;
    b = a++;

    cout <<"a"<<a<< endl;
    cout <<"b"<<b" endll
    ...ect

    a = 1;
    b = ++a;

    cout <<"a"<<a<< endl;
    cout <<"b"<<b" endll
    ...ect
    Output:

    a = 2, b = 1
    a = 2, b = 2
    Actually I was understand that the function of these operators, but sometimes I was thinking logically. The question is >> why a = 2?? I know the post-increament and post-decreament, but why a is 2?

    It's clearly that when the code printed the a value, it's 1 not 2. The cout statement meant "print" the value of a, the value is 1, when the code executed why the a value become 2?

    Logically in human language is:

    print a = ... a value end of line
    print b = ....b value with ++ operator end of line

    You see? print a, a = 1. But why the output is 2??

    Hmmm...I'm sorry, I don't really get it. Can the forum members can explain to me in human language?

    Thank you so much if you'all will...

    Best regards,

    Kris

  2. #2
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,842

    Re: The x++ and ++x Operators

    Hi. To format your code properly, Go Advanced, select the code then click '#'

    Code:
    b = a++;
    means that b is assigned the value of a and then a is incremented by 1

    Code:
    b = ++a;
    means that a is incremented by 1 and the new value of a is assigned to b

    a++ or ++a always means that a is incremented by 1 where-ever the statement appears. The only difference is if the result is used, like in the assignments, is whether the value is the original (a++) or new (++a).
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center