Side Effects

A "side effect" is, roughly speaking, a change in the status of a program caused by the actions of a subprogram that can not be anticipated by a casual reading of the subprogram's header or a statement that calls upon the subprogram. Side effects are undesirable, because their presence complicates understanding of the totality of a program's actions, and they work against software reusability, a major goal of object oriented programming. Further, they are almost always easily avoided.

Unfortunately, a mature culture of C++ programming has arisen in which, in many circles, it's considered alright to use side effects. I prefer to discourage them. You are hereby warned that side effects will be considered negatively when I grade your projects.

One source of side effects is the usage of a variable "globally." This refers to the use of a variable in a subprogram that neither appears in the subprogram's list of parameters nor in its local variables. Since the variable is not used as an actual parameter by the statement that calls upon the subprogram using the variable globally, a change in the value of the variable by the actions of the subprogram cannot be anticipated by a casual reading of either the calling statement or the function header. Such a side effect is easily avoided by passing the information shared by the caller and the subprogram through the subprogram's parameter list.

Other ways in which side effects may appear are associated with C++ functions that are not declared "void" -- such a function is expected to return a value, so that it is a "function" in the mathematical sense, namely, producing exactly one new data value for its caller that is completely determined by the values of the actual parameters in the calling statement's parameter list. Thus, if either more than one new data value is produced, or if output is produced (which represents a kind of new data), or if the action of the function is not completely determined by its parameter list (e.g., perhaps input executed during the function's execution helps determine the function's value), our understanding of "function" in the mathematical sense is violated; hence, a casual reading of the function header misleads us as to the type of effects we should expect the function to have on its caller.

It follows from the remarks above that, in a C++ function that is not "void," all of the following represent side effects:

Each of the latter group of side effects is easily avoided by making the subprogram in question a "void" function and by letting the value we had intended to pass as the value of the function be, instead, a parameter passed by reference. A void subprogram is not expected to act as a mathematical function, hence may (without surprise) pass multiple parameters by reference and perform i/o. (It still should not use a variable globally.)


Back to Boxer's Home Page