CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Mar 2013
    Location
    Spring Hill, TN
    Posts
    2

    Issue with the suffix increment operator(++) in a cout statement.

    Hello, I am teaching myself C++ as a hobby and I encountered an example in the book which compiles but does not produce the intended output.
    Here is the code:

    // Ex8_09.cpp
    // Creating and joining string objects
    #include <iostream>
    #include <string>
    using std::cin;
    using std::cout;
    using std::endl;
    using std::string;
    using std::getline;

    // List names and ages
    void listnames(string names[], string ages[], size_t count)
    {
    size_t i = 0;
    cout << endl << "The names you entered are: " << endl;
    while(i<count && !names[i].empty())
    cout << names[i] + " aged " + ages[i++] + '.' << endl;
    }

    int main()
    {
    const size_t count = 100;
    string names[count];
    string ages[count];
    string firstname;
    string secondname;

    for(size_t i = 0 ; i<count ; i++)
    {
    cout << endl << "Enter a first name or press Enter to end: ";
    getline(cin, firstname, '\n');
    if(firstname.empty())
    {
    listnames(names, ages, i);
    cout << "Done!!" << endl;
    return 0;
    }

    cout << "Enter a second name: ";
    getline(cin, secondname, '\n');

    names[i] = firstname + ' ' + secondname;
    cout << "Enter " + firstname + "'s age: ";
    getline(cin, ages[i], '\n');
    }
    cout << "No space for more names." << endl;
    listnames(names, ages, count);
    return 0;
    }

    I may be wrong, but the problem seems to be in the function "listnames". Specifically, the output statement inside the while loop. I don't understand
    how the ++ operator is behaving in this statement. The output produced does not match what's printed in the book. I usually just type all the
    examples, but with this one I also downloaded the source code from the book's website to make sure the error wasn't due to mistyping. I would
    greatly appreciate any help that would explain what is going on.
    appreciate

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Issue with the suffix increment operator(++) in a cout statement.

    Quote Originally Posted by luisdtor View Post
    Hello, I am teaching myself C++ as a hobby and I encountered an example in the book which compiles but does not produce the intended output.
    That is because there is no "intended output" with that cout statement.

    First, please use code tags when posting code. The code you posted is almost unreadable.

    Second:
    Code:
       cout << names[i] + " aged " + ages[i++] + '.' << endl;
    This is ambiguous as to when i will be incremented. Describe to us when you think i is incremented. Whatever it is, another person will say something different as to when i is incremented, thus you and the other person give different results. That is exactly the situation between the compiler your book used and the compiler that you're using now -- ambiguity.

    In C++, there is something called sequence points. Basically, adjusting the same variable more than once within the same statement (i.e. sequence point) is undefined behaviour. So there is no answer as to what that statement should output. It is no different than this:
    Code:
    int i = 0;
    cout << i++ + ++i;
    So what should be outputted for "i"?
    The output produced does not match what's printed in the book.
    What book is this? No good C++ book would present code like this, unless the book's intent is to show you an ambiguous usage of the ++ operator.

    Edit: It seems you copied the example wrong from this book:

    http://books.google.com/books?id=H1w...ed=0CDMQ6AEwAQ

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; March 8th, 2013 at 03:49 AM.

  3. #3
    Join Date
    Oct 2008
    Posts
    1,456

    Re: Issue with the suffix increment operator(++) in a cout statement.

    I've not read all the code ( please, next time use [ code ] ... [ /code ] tags ) nor I have run it, but the line "cout << names[i] + " aged " + ages[i++] + '.' << endl; " in the function "listnames()" gives undefined behavior, so the program could behave inconsistently with respect to the 'i' variable value, or could behave normally, or could even crash ( well, in theory, at least ).

    Essentially, you cannot read and write more than once a scalar object ( = an int, a pointer, etc... ) in the same expression.
    More precisely, the technical reason depends on to which c++ standard you're compiling against.
    In c++2003, observable effects of evaluation of expressions ( called "side effects" ) are sequenced at precise subexpressions ( called "sequence points" ), like the ";" at the and of a full subexpression, or a function call, etc... . Invoking more than one side effect on a scalar object in between two consecutive sequence points gives undefined behavior.
    In c++11, the sequencing of side effects obeys to a more general model ( a multithreaded abstract machine ); anyway, the situation is similar : invoking more than one unsequenced side effects on a scalar object gives undefined behavior.

    So, things like "i=i++", "i++ + i++", etc... all have undefined behavior in C++.

    Now, your specific case is a bit more subtle because the 'i' accesses are separated by a number of function calls ( the +operators ) whose evaluation is sequenced with respect to their arguments ( although their evaluation order remains unspecified ). Nonetheless, the language requires that the condition described above of an unsequenced multiple read/write on a scalar object will give undefined behavior whenever it holds for some possible arrangement of the evaluation tree.

    EDIT: sorry, I missed Paul's reply ...

  4. #4
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Issue with the suffix increment operator(++) in a cout statement.

    Quote Originally Posted by luisdtor View Post
    I may be wrong, but the problem seems to be in the function "listnames". Specifically, the output statement inside the while loop. I don't understand
    how the ++ operator is behaving in this statement. The output produced does not match what's printed in the book. I usually just type all the
    examples, but with this one I also downloaded the source code from the book's website to make sure the error wasn't due to mistyping. I would
    greatly appreciate any help that would explain what is going on.
    appreciate
    If this code is presented as an example in your book, then get rid of it and find yourself a good book.
    Besides the undefined behavior pointed out in previous posts, the logic of the while loop is also flawed.
    Code:
      size_t i = 0;
      while(i<count && !names[i].empty()) {
        // print something
        ++i;
      }
    What do you think would happen if names had, say, 3 items and the second is an emtpy string?

    When you loop over a container whose size is not changed in the loop, it's typically best to use a for-loop. It makes it easier to avoid these kinds of problems.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  5. #5
    Join Date
    Mar 2013
    Location
    Spring Hill, TN
    Posts
    2

    Re: Issue with the suffix increment operator(++) in a cout statement.

    Thank you all for the help. After I studied your replies and researched a bit on sequence points in C++, I think I understand. Let me put it in my own words and please feel free to correct me if I'm wrong. In the statement "cout << names[i] + " aged " + ages[i++] + '.' << endl; ", the array sub-scripting operator [] is overloaded for the standard string class. Overloaded operators are implicit function calls. So the above code statement can be written in a more general form: "cout << f() + pstr1 + g() + pstr2 << endl;". According to the rules of C++ sequence points, in any expression "f() + g()" where f and g are functions, the order in which f and g are evaluated is ambiguous. The value of i that is passed into these functions depends on the order that they're evaluated in. But if the order is ambiguous, then the result of the entire statement is undefined.

    In case you're curious, the book I am using is "Ivor Horton’s Beginning Visual C++ 2008", and the code in question is on page 474.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured