Why do I need in and out in the memory copy function?

I found an example where the function for copying content from one memory area to another takes three arguments: the source memory area (param[out]), the target (param[in]), and the number of bytes to copy (param[in]).

I don't quite understand the difference between in and out. What are these values for?

Author: Kromster, 2016-12-14

1 answers

Since you probably did not specifically indicate where exactly you got this documentation, my answer may be a little different from what will be written there, but ideologically it will be close.

The "classic functions" have all the arguments "in" - that is, incoming. They are subject to one requirement - they must be read-only, and if the function inside changes them, the external code will not know about it. Usually, such arguments can be passed directly (for example, just a number), so is the variable / expression.

But sometimes you need to pass an argument inside the function that you can change. Yes, classical functions usually return a result, but sometimes this is not enough. In this case, just "out"is needed. A classic example is passing a pointer to a variable. A function inside itself can write a value there and the calling code will "see" it.

Moreover, if the in parameter must contain a meaningful value (except if it is not used inside), then out may well not be initialized.

Some compilers treat parameters as in by default, and you need to explicitly specify out (pascal, delphi, C#). Moreover, the compiler can even check whether a value is returned. Of course, there are always workarounds and you can fool the compiler:).

Let's look at the classic view of the memory copy function

void * memcpy ( void * destination, const void * source, size_t num );

Initially, it is not quite clear what is what (for novice programmers). But if to say that destination is out, a source and num in, then the situation becomes a little clearer (although the names themselves seem to hint). In this case, as it were, there is a guarantee that what is passed by the source will not change (there, by the way, const once again hints). And what will be stored at the destination address-will change-in the same place out.

Let's sum it up. In most cases (if it's c / c++, assembler), in/out are just conventions (and there are no such keywords). In other languages, the compiler can check a little (pascal, C# and they even have such words). It is quite possible that there are programming languages that contain stricter rules and may even refuse to compile if the declaration diverges from the code. The gcc compiler has special keywords (these are already extensions) that partially implement this as well. Plus, the compiler can trust you and do the optimization.

 6
Author: KoVadim, 2016-12-14 09:31:03