Function parameter in c++

  • void f(int i) {} -- this function expects to get one int parameter and returns nothing.
  • void f(int *i){} -- this one is waiting for a pointer, I understand.
  • void f(int &i){} -- what does this function expect at the input?
Author: Vlad from Moscow, 2019-01-02

2 answers

In short, we can say the following.

The parameter of this function is

Void f(int &i){}

Defines a so-called lvalue reference.

This function definition allows you to change the argument passed to the function, since the function is not passed a copy of the argument value, but the argument is passed by reference. For example,

#include <iostream>

void g( int i )
{
    i += 10;
}

void h( int &i )
{
    i += 10;
}

int main() 
{
    int i = 0;

    std::cout << "Before call g( i ) i = " << i << '\n';
    g( i );
    std::cout << "After  call g( i ) i = " << i << '\n';

    std::cout << '\n';

    std::cout << "Before call h( i ) i = " << i << '\n';
    h( i );
    std::cout << "After  call h( i ) i = " << i << '\n';

    return 0;
}

Program output to the console

Before call g( i ) i = 0
After  call g( i ) i = 0

Before call h( i ) i = 0
After  call h( i ) i = 10

That is, the function g deals with a copy of the value of the variable i. The original one itself the i variable declared in main does not change.

On the other hand, the function h modifies the original variable i, since it is passed to the function by reference.

Keep in mind that you can also declare a function parameter as

int &&i

This is a so-called rvalue reference designed for working with temporary objects.

Consider such a program.

#include <iostream>

void f( int && )
{
    std::cout << "void f( int && )\n";
}

void f( int * )
{
    std::cout << "void f( int * )\n";
}

void f( int & )
{
    std::cout << "void f( int &  )\n";
}

int main() 
{
    int i = 0;

    f( 0 );

    f( i );

    f( &i );

    return 0;
}

Its output to the console:

void f( int && )
void f( int &  )
void f( int * )
 1
Author: Vlad from Moscow, 2019-01-02 17:26:58

Short answer: this function expects an lvalue of type int. Parameter-link i will be bound to the lvalue that you pass as an argument.

Long answer: Read the literature on references in C++. References in C++ are a basic property of the C++ language and are too broad a topic to attempt to cover in a single answer.

What is the difference between references and pointers in C++

 0
Author: AnT, 2019-01-02 16:56:46