How are side effects and observable behavior related in C++?
Asked Answered
C

1

14

C++03 Standard 1.9/6 defines observable behavior:

The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions.

and then and then 1.9/7 defines side effects:

Accessing an object designated by a volatile lvalue (3.10), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment.

Is a side effect an observable behavior or not? How are they related to each other?

Clementeclementi answered 7/11, 2012 at 14:11 Comment(0)
W
16

No, a side effect is not necessarily observable behaviour. Modifying a non-volatile object, for example, is a side effect, but not observable. The difference matters because the side effects may be rearranged or removed altogether by the compiler, so long as the observable behaviour remains the same.

int main()
{
    int a;
    a = 30;
    a += 2;
    return 0;
}

Most compilers will, if requested, remove a completely. That's permitted. The assignments and addition aren't observable.

All observable behaviour must necessarily be a side effect though.

Wanderlust answered 7/11, 2012 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.