answersLogoWhite

0

You obviously cannot have a function that is both void and non-void; it must be one or the other.
Let us suppose we have a function that accepts two arguments and returns the product of those arguments:

int x = product (6, 7);

Here we would expect x to hold the value 6x7=42. In order for this function to work we must define it as follows:

int product (int a, int b) { return a*b; }

Clearly this is the most intuitive way to define this function. It is also the most flexible because it allows us to do the following:

x = product (x, x);

Here the value of x will be 1764 if the original value of x was 42.

Note that the value of x is not changed by this function, it is changed by the assignment operator (=). As far as the function is concerned x does not actually exist because the arguments were passed by value and those values (42 and 42) were assigned to its formal arguments, a and b.

If we were to use an output parameter rather than a return value, the function becomes less intuitive. We could use one of the input arguments as the output parameter, however this makes it even less intuitive. Instead, we'll use a separate argument:

void product (int a, int b, int* result) { *result=a*b; }

The problem with this is that we might pass a null pointer:

int* z = NULL;
product (6, 7, z); // error!

The function takes no account of this possibility and the end result will be undefined behaviour. We can obviously fix this with a simple test for null before we attempt to dereference the pointer:

void product (int a, int b, int* result) { if (result!=NULL) *result=a*b; }

The problem with this is that we are now performing a conditional branch every time we invoke this function even though the exception should really be a rare occurrence. Unfortunately there is no way to optimise this function, but the reason we have this branch is entirely due to a poor design choice.

If we need to return a single value, then it makes sense to use the return value itself. It is clearly more intuitive and it lets the caller decide exactly what they want to do with the return value.
User Avatar

Wiki User

9y ago

What else can I help you with?

Continue Learning about Engineering
Related Questions