Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IN/OUT Parameters and how to work with them in C++

Tags:

c++

parameters

When reading documentation on functions from external libraries of different kinds I have always seen the documentation state that a variable has to be [IN/OUT]. Could someone give me a detailed understanding on how [IN/OUT] relates to parameters of a function being passed by reference or by value.

Here is an example of a function I have come across that tells me it needs an [IN/OUT] parameter:

Prototype: ULONG GetActivationState( ULONG * pActivationState );

Parameters

  • Type: ULONG*
  • Variable: pActivationState
  • Mode: IN/OUT
like image 932
danes Avatar asked Aug 01 '11 14:08

danes


1 Answers

This parameter is in/out because you provide a value that is used inside the function, and the function modifies it to inform you about something that happened inside the function. The usage of this function would be something like this:

ULONG activationState = 1; // example value
ULONG result = GetActivationState(&activationState);

note that you have to supply the address of the variable so that the function can get the value and set the value outside the function. For instance, the GetActivationState function can perform something like this:

ULONG GetActivationState(ULONG* pActivationState)
{
    if (*pActivationState == 1)
    {
    // do something
    // and inform by the modification of the variable, say, resetting it to 0
       *pActivationState = 0;
    }
    // ...
    return *pActivationState; // just an example, returns the same value
}

Note how:

  1. The function accepts the parameter as a non-const pointer to an UINT. This means it may modify it.
  2. The function can access the value you gave to the parameter by dereferencing it
  3. The function can modify the parameter again by dereferencing it.
  4. The calling function sees the activationState variable holding the new value (0 in this case).

This is an example of "pass by reference", which is performed by using pointers in C (and also with references in C++.)

like image 184
Diego Sevilla Avatar answered Nov 09 '22 13:11

Diego Sevilla