> On 9/16/20 5:43 PM, Juha Nieminen wrote:
>> Rick C. Hodgin <
rick.c...@gmail.com> wrote:
>>> You wouldn't write IO in that way in C, so the problem goes away.
>> Oh, so nobody ever writes things like
>> printf("%i,%i", a(), b())
>> in C?
>
> You tell me. Per the bug report he submitted to Visual Studio 2019:
>
> int a(void)
> {
> return 1;
> }
>
> int b(void)
> {
> return 2;
> }
This is not "per the bug report". You picked these, possibly unaware
that they are useless examples. The bug report and no explicit a and b.
> int main(int argc, char* argv[])
> {
> // C++ way
> std::cout << a() << b();
> std::cout << std::endl;
> // Reports 12
As it must. Your a() and b() can't illustrate the problem, because it's
about side effects.
> // C++ way
> std::cout << (a() << b());
> std::cout << std::endl;
> // Reports 4
The issue is about operator precedence and parentheses.
> // C way
> printf("%d\n", a() << b());
The C equivalent of the original posted code is (depending on the return
type)
printf("%d,%d\n", a(), b());
and suitable examples to show a potential sequencing bug might be
int a(void) { fprintf(stderr, "a called\n"); return 1; }
int b(void) { fprintf(stderr, "b called\n"); return 2; }
(writing (void) because these are being used in C and C++ code).
Prior to C++17,
std::cout << a() << "," << b() << "\n";
could produce either
a called
b called
or
b called
a called
on stderr, though always
1,2
on stdout. C++17 added a rule that in E1 << E2, E1 is sequenced before
E2. That is a statement about when any side effects must be seen to occur,
and is not about operator precedence.
In C, the "problem" (if one chooses to see it as one), persists to this
day. All function argument evaluations are sequenced before the call,
but are unsequenced with respect to each other. In this case, a and b
must both be called and any side effects completed before the call to
printf, but a and b can be called in either order.
> // Reports 4
>
> return 0;
> }
>
> I only have Visual Studio 2003 on this computer, and it reports 12, 4,
> and 4. It should be reporting 4, 4, and 4, in C++17.
Your example a() and b() can't show the issue.
> C gets it right. C++ does too with a little help from its friends
> (parenthetically speaking of course).
It's not about parentheses.
>> Right...
>
> See how easy it is to misunderstand something? You do it
> effortlessly. You make it look easy. :-)
And here's a smilie. So was the above just all a big joke too? No
matter; maybe someone else will get something from reading it.
> Actually, this would be a great teaching moment for Bonita. It
> demonstrates that adding an extra set of parenthesis now and then
> removes real-world code issues.
Parentheses can't help.
--
Ben.