Like Tree2Likes
  • 1 Post By iMalc
  • 1 Post By oogabooga

Increment Operator Results

This is a discussion on Increment Operator Results within the C++ Programming forums, part of the General Programming Boards category; Hi, I'm currently enrolled in programming fundamentals for computer science class at the local community college. Testing out what the ...

  1. #1
    Registered User heisenbug's Avatar
    Join Date
    Sep 2013
    Location
    Los Angeles, CA.
    Posts
    3

    Increment Operator Results

    Hi,

    I'm currently enrolled in programming fundamentals for computer science class at the local community college.

    Testing out what the results would be if I use a++ and ++a where a is a variable of integer data type initialized to 0.

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    
    int a = 0;
    
    cout << "a++ = " << a++ <<endl;
    cout << "++a = " << ++a <<endl;
    cin.get();
    
    return 0;
    
    }
    When I run the program, I get different results.
    a++ prints out 0 and ++a prints out 1.

    If both a++ and ++a increment the value of variable a by 1, why are the results different? Can someone point me in the right direction?

    Thank you
    Attached Images Attached Images   

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,681
    Welcome to the forum. Nice first post by the way. Thee only thing I would advice you, is to copy paste your output as code and note that this is my output. You see, the images take more space, than the output.

    Your code is equivalent to this code: (post-fix case)
    Code:
    #include <iostream>
    using namespace std;
     
    int main()
    {
     
         int a = 0;
    
         cout << "a++ = " << a <<endl;
         a = a + 1; // We increment 'a' after we "execute" the cout
         cin.get();
     
         return 0;
     
    }
    while the pre-fix case would something like this:
    Code:
    #include <iostream>
    using namespace std;
     
    int main()
    {
     
    int a = 0;
     
    a = a + 1; // We increment 'a' before we "execute" the cout
    cout << "++a = " << a <<endl;
    cin.get();
     
    return 0;
     
    }
    So, in pre-fix case, the operations of addition will be executed before the line of code, that this increment operator lies into, gets executed.

    On the other hand, post-fix case will execute the line of code and the operation of addition by one will be executed.

    However, try not to cause undefined behavior with them. If you keep it simple, you will not.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    To elaborate, do not modify the same variable twice in the same statement (or line). a++ + ++a is undefined behaviour.
    Postfix and prefix operators are also good when used in simple expressions, such as when they're alone on the right hand side of an operator (eg b = a++). But if you have a more complex expression, beware. The order of evaluation of subexpressions is undefined, so ++a + ++b, while okay, does not say if a will be incremented first and then b, or the other way around. It can have unintended consequences.
    Welcome to the world of C++.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    If you run that whole program as shown, it will print out a++ = 0 and then ++a = 2.

    Why?
    Because it prints the value of a, then increments a, then it increments a, and finally prints out a again.
    Elkvis likes this.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User heisenbug's Avatar
    Join Date
    Sep 2013
    Location
    Los Angeles, CA.
    Posts
    3
    Hi,

    Thank you std10093, Elysia and iMalc for your time and explanations.

    It is my mistake not to give a clear explanation of what I was asking for and may be a bad code example I gave.

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    (    
    
    int x;
    int y;
    
    
    x = 5;
    y = x++;
    cout << "The value of y with post increment operator: " <<y <<endl;
    cout <<"The value of x: " << x <<endl;
    
    x = 5;
    y = ++x;
    cout << "The value of y with pre increment operator: " << y <<endl;
    cout << "The value of x: " << x <<endl;
    
    cin.get();    
    return 0;
        
    }
    
    Here is my output:

    The value of y with post increment operator: 5
    The value of x: 6
    The value of y with pre increment operator: 6
    The value of x: 6

    My question is,

    Why in the case of a post increment operation, the initial value of x was assigned to y and then x got incremented by 1.
    Whereas in the case of pre increment operation, the value of x got incremented by 1 first and then the assignment took place.

    From doing google searches, someone said that

    ++x increments and produces as expression result x as an lvalue while,
    x++ increments and produces as expression result the original value of x.

    Obviously at this point I don't know what an lvalue is.

    The instructor taught us that expressions on the right hand side are evaluated first and then the result is assigned to the variable on the left hand side. Following this logic, then I would think in the case of x++, it should expand to an expression x + 1, get evaluated and only then the result should be assigned to y.

    Is my understanding incorrect?

    Thank you.
    Last edited by heisenbug; 09-13-2013 at 10:41 AM. Reason: Poor Indentation.

  6. #6
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    The ultimate effect of both forms of increment operator is to add one to the variable. But the value returned by the expressions are different. In the pre-increment, the expression's value is the variable's value after the increment. In the post-increment, the expression's value is the variable's value before the increment.

    Here's an example of implementing the increment operators in a class. Note that for the post-increment, we need to save the old value, add one to the variable, and then return the old value.
    Code:
    #include <iostream>
    
    class A
    {
        int m_n;
    
    public:
    
        A(int n) : m_n(n)
        {
        }
    
        A operator++()       // pre-increment operator:  ++a
        {
            ++m_n;
            return *this;
        }
    
        A operator++(int)    // post-increment operator:  a++
        {                    // (The unnamed int parameter is a
                             // "kludge" to indicate post-increment.)
            A ret(*this);
            ++m_n;
            return ret;
        }
    
        friend std::ostream& operator<<(std::ostream& os, A a);
    };
    
    // operator<< overload so object can be printed with cout
    std::ostream& operator<<(std::ostream& os, A a)
    {
        return os << a.m_n;
    }
    
    int main()
    {
        A a1(0);
        std::cout << a1++ << '\n';   // prints 0
    
        A a2(0);
        std::cout << ++a2 << '\n';   // prints 1
    
        return 0;
    }
    Last edited by oogabooga; 09-13-2013 at 11:11 AM. Reason: fixed operator implementation
    vart likes this.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    Quote Originally Posted by heisenbug View Post
    Why in the case of a post increment operation, the initial value of x was assigned to y and then x got incremented by 1.
    Whereas in the case of pre increment operation, the value of x got incremented by 1 first and then the assignment took place.
    Because that is precisely what the intended difference between pre and post-increment is.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User heisenbug's Avatar
    Join Date
    Sep 2013
    Location
    Los Angeles, CA.
    Posts
    3
    Hi,

    oogabooga: Thank you. The code example you provided is above and beyond my current knowledge.

    iMalc: Thank you.

    The official curriculum book the school is following is called,
    C++ Programming From Problem Analysis to Program Design by D.S. Malik.
    We are currently reading chapters 2 & 3.

    Thank you & Have a great weekend.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. increment operator
    By Rohit88 in forum C Programming
    Replies: 5
    Last Post: 07-29-2013, 01:39 PM
  2. pre-increment operator..
    By narendrav in forum C Programming
    Replies: 6
    Last Post: 05-02-2013, 01:57 AM
  3. Increment operator
    By ssharish2005 in forum C Programming
    Replies: 8
    Last Post: 06-06-2011, 04:32 PM
  4. Increment Operator
    By theunderdog118 in forum C Programming
    Replies: 4
    Last Post: 05-31-2010, 11:00 AM
  5. Increment Operator
    By anirban in forum C Programming
    Replies: 5
    Last Post: 11-25-2008, 07:25 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21