I have read many discussions of what constitutes a "side effect" in C, and many seem to indicate that it must involve changing something that is not local to the function causing the change. Changing an external variable or a file are the typical types of things the discussions say have to be changed to qualify as a side effect. The discussions also commonly imply that merely changing the value of a local automatic variable in the same block in which it is declared is not a side effect. However, 5.1.2.3.2 of the C17 standard states the following:
Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects,12) which are changes in the state of the execution environment.
My understanding from C17 6.2.4.1 is that all variables (among other things) represent objects. If that is the case, wouldn't changing the value of any variable regardless of scope or storage class qualify as a side effect?
CodePudding user response:
If that is the case, wouldn't changing the value of any variable regardless of scope or storage class qualify as a side effect?
Yes.
Consider the code a = 3; printf("%d\n", a );
. This prints “3”, because the main effect of a
is to produce the value of a
for the expression, and the value of a
is 3. The code also changes the value of a
, and that is a side effect.
Consider printf("%d\n", (a = 3) * 4);
. The main effect of the assignment expression, a = 3
, is to produce the new value of the assigned object, so its value is 3
. Then that is multiplied by 4, so printf
prints “12”. As a side effect, the stored value of a
is changed to 3.
Also, printf
writes to standard output, and that is also a side effect.