Fun surprising things
Neia Neutuladh
neia at ikeran.org
Thu Nov 1 04:58:55 UTC 2018
On Thu, 01 Nov 2018 00:39:17 -0400, Nick Sabalausky (Abscissa) wrote:
> On 10/31/18 10:00 AM, bauss wrote:
>> What's the output of this program? (Try to figure it out without
>> running it.)
>>
>> ```
>> int c = 0;
>>
>> int a()
>> {
>> return c++;
>> }
>>
>> int b()
>> {
>> return c--;
>> }
>
> I'm not sure I understand the point here. I mean, who writes code like
> that? Pre/Post-incement operators? Combined with globals? To me that
> just smells of trouble.
class Connection
{
Socket socket;
int readInt() { /* read an int from the socket somehow */ }
float readFloat() { /* read a float from the socket */ }
void doSomethingFunky()
{
writeln(to!string(readInt()) ~ to!string(readFloat()));
}
}
It's not great, but it doesn't deal with pre/post increment operators or
global variables. The point is that both sides of the expression have side
effects altering the same data. What happens should be well-defined.
A global variable and increment operators are condensed ways of showing
what's going on.
> So if the issue is that the above code should result in an error but
> currently doesn't, then...honestly, I'm totally onboard with that,
> because it definitely strikes me as bad code. But I'm unclear about the
> details. What *exact* part of it should be the error? To me, that's the
> part that's not obvious. Intuitively, it strikes me as as bad code, but
> to me, it's not obvious what *specifically* the compiler should be
> objecting to. So, at least for me, spelling this out in more detail
> would really help.
If you don't introduce whole-program analysis, your error is that the
operands are not pure / immutable.
If you do introduce whole-program analysis, your error is that both sides
of the expression modify the same mutable state, and the return value is
dependent on that state.
Except that's only applicable if the spec doesn't define the appropriate
order of evaluation.
More information about the Digitalmars-d
mailing list