Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

It is obvious that first cout prints 7 7 but why the second one prints 8 8 7 ? Why not 7 8 8? How does such constructions work in c++?

int ink(int *x){
     *x += 1;
     return *x;
}
int main(){
    int *a;
    int b = 6;

    a = &b;

    cout << ++b << " " << b << endl;   
    cout << b << " " << ink(a) << " " << b;

    return 0;

}

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

Because the code contains side effects. You can't be sure in what order the elements will be executed.

Here is some more info: http://en.wikipedia.org/wiki/Sequence_point

EDIT: Here is the output on my machine:

7 6
8 8 7

As you can see it's different from yours. The correct approach is to make all calculations before the cout and then pass the values only.

share|improve this answer
add comment

It may be easier to understand what's going on if you look at the chain of function calls that the second one devolves to (I'm using the operator defs here, which do match the gcc headers on my system):

cout << b << " " << ink(a) << " " << b;

operator<<(operator<<(cout.operator<<(b)," ").operator<<(ink(a)), " ").operator<<(b);

Aside: This looks very odd because the numeric inserters are all methods of the object, while the character string inserters are all global functions, which makes the call order even more strange than it might be.

Now that you have the actual call chain, you can see how it would end up putting the 7 on the stack before the 'ink' call, but actually won't use that until well after, thus causing the non-intuitive outputs.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.