Michael White <michael_whi...@...> wrote:
> ...Everything to the right of the assignment operator '='
> happens first.
There is no guarantee in C or C++ of that being the case.
Unlike some other languages, = is just another operator.
In C and C++, side effects are only guaranteed between
sequence points. Some operators, like && (and) and || (or)
will impose additional sequence points, however simple
assignment is not one of them.
The program below has additional sequence points from the
function calls, however it should be obvious that (on my
implementation at least) there is no guarantee that the
right hand sub-expression of = will be evaluated _before_
the left one.
% type sp.cpp
#include <iostream>
using namespace std;
int a = 0;
int b = 42;
int *f()
{
cout << "f(): a = " << a << "; b = " << b << endl;
return &a;
}
int g()
{
cout << "g(): a = " << a << "; b = " << b << endl;
return b;
}
int main()
{
*f() = g();
cout << "main(): a = " << a << "; b = " << b << endl;
}
% app sp.cpp -o sp.exe
% sp.exe
f(): a = 0; b = 42
g(): a = 0; b = 42
main(): a = 42; b = 42
%
> So, even if you wrote your code as '++a' or as 'a++', 'a'
> would still get incremented before the line gets assigned
> to 'c'.
Chapter and verse from the standard, please. You may be
thinking of overloaded = operators, but that doesn't apply
in ordinary assignments.
--
Peter