← Back to context

Comment by jacquesm

5 years ago

That's a C/C++ trick where a location to dump the output is presented as an argument to the function. This makes functions un-pure and leads to all kind of nastiness such as buffer overruns and such if you are not very careful.

sprintf(buffer,"formatstring", args)

'buffer' is an output argument.

It's wrong to call output parameters a "C/C++ trick" because the concept really has nothing to do with C, C++, buffer overruns, purity, or "other nastiness".

The idea is that the caller tells the function its calling where to store results, rather than returning the results as values.

For example, Ada and Pascal both have 'out' parameters:

    https://stackoverflow.com/questions/3003480/the-use-of-in-out-in-ada#3004067

    https://freepascal.org/docs-html/ref/refsu66.html#x182-20600014.4.3

    http://www.ada-auth.org/standards/rm12_w_tc1/html/RM-6-1.html

Theoretically, other than different calling syntax, there's conceptually no difference between "out" parameters and returning values.

In practice, though, many languages (C, C++, Java, Python, ...) support "out" parameters accidentally by passing references to non-constant objects, and that's where things get ugly.

Not only in C land; C# has "ref" (pass by reference, usually implying you want to overwrite it) and "out" (like ref but you _must_ set it in all code paths). Both are a bit of a code smell and you're nearly always better off with tuples.

Unfortunately in C land for all sorts of important system APIs you have to use output arguments.