<< question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ralf Goertz

    << question

    (second repost, there seem to be problems)

    Hi,

    this might be g++-related but it raises a general question.

    #include <iostream>

    using namespace std;


    bool getValue(int& val){
    val=int(42);
    return true;
    }

    int main(){
    int i(0);
    cout<< i<<" "<<getValue(i)< <" value "<<i<<endl; // (*)
    }


    Compiled with optimization (-O3) this yields the output
    42 1 value 42
    Without optimization it gives
    42 1 value 0
    I had expected
    0 1 value 42
    Do I have to read the line (*) from right to left? But that seems odd
    since "endl" is at the end of the output.

    Ralf
  • Juha Nieminen

    #2
    Re: &lt;&lt; question

    Ralf Goertz wrote:
    bool getValue(int& val){
    val=int(42);
    return true;
    }
    >
    int main(){
    int i(0);
    cout<< i<<" "<<getValue(i)< <" value "<<i<<endl; // (*)
    Because your getValue() function has side effects, the results of that
    last expression are undefined because there's more than one reference to
    the value being modified in the same expression. This is because the
    compiler is allowed to optimize that kind of expression in any way it
    wants. The result is only guaranteed after the ';'.

    If you want it to work "correctly" , divide each reference to 'i' into
    its own expression:

    cout << i << " ";
    cout << getValue(i);
    cout << " value " << i << endl;

    Comment

    Working...