1
int i = 7, j = 3;
int *a = &i, *b = &j;
cout << (*a = *b) << ", " << *(*(&a));

Can someone please explain why is the output 3, 7?

CinCout
  • 9,486
  • 12
  • 49
  • 67
Ned
  • 57
  • 5
  • 7
    Order of evaluation of function arguments is undefined. All the faffing with pointers is just confusing the matter. – BoBTFish Dec 19 '16 at 09:11
  • I'm a noob and this was from our programming class' previous exam. I just typed this into Code::Blocks and the answer I got was 3, 7. I don't know why, so I'm asking here... – Ned Dec 19 '16 at 09:17
  • My answer was just the very short version of alexeykuzmin0's. But I guess if you didn't know why you got this output, you probably had some reason to expect some specific different output (it is often helpful to included this sort of information in your question, but that doesn't matter now), which was probably because you expected the arguments to be evaluated in a particular order: left-to-right. I didn't mean for the terseness of my comment to suggest that it was obvious or you had done something stupid. I just didn't have time to write out a full answer. – BoBTFish Dec 19 '16 at 09:20
  • Do you ask, why the value `a` is pointing to is one time 3 and the other time 7 or do you have problems understanding the syntax? – izlin Dec 19 '16 at 09:24
  • I expected to get 1, 3 because I thought (*a = *b) will return 1, and *a, which was previously 7, will become 3 because of (*a = *b). – Ned Dec 19 '16 at 09:27
  • 2
    Wait, didn't I see the same, exact question, posted few hours ago? EDIT: ah, [here it is](http://stackoverflow.com/questions/41214994/assignment-statement-in-cout-statement-c). – Algirdas Preidžius Dec 19 '16 at 09:30
  • Thanks everyone. Why is there such a stupid question in a university's final exam... – Ned Dec 19 '16 at 09:34
  • 1
    @Ned You should ask your lecturer about that. We don't know why would anyone put such a question in an exam. – Algirdas Preidžius Dec 19 '16 at 09:37

1 Answers1

6

Your code can be simplified:

int i = 7, j = 3;
cout << (i = j) << ' ' << i;

Here the variable i is accessed and changed in the same statement. Since the order of evaluation of different parts of the same statement is not specified in the C++ standard, compiler may calculate them in any order, and the result may be different on different compilers (or even different versions of the same compiler, or different runs of the same compiler on the same source code, or even different runs of the same compiled program).

Don't write code that changes and accesses something in one statement.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51