Home


Lesson 5

Pointers to fuctions

Task 0

Analyse all * in the code below:


#include <iostream>

int give2()
{
    return 2;
}

int main()
{
    int  fun0; // int variable
    int *fun1; // pointer to int variable

    int *fun2();  // header of a function, which returns a pointer to int variable
    
    int (*fun3)(); // pointer to a function, which returns int
    int *(*fun4)(); // pointer to a function, which returns a pointer to int

    fun3 = &give2;
    std::cout << fun3() << std::endl;

}
Task 1: Russian roulette

Write a function lucky(), wchich returns one (1/6 chance) or second (5/6 chance) function.

Goal of the first one is to display "Lose", the second "Win".

Call a function returned by lucky().

Task 2: Calculus

Write a method, which will calculate an integral of any given function.

Create 3 different functions and use as arguments.

Warning: we will use distinct integral.

Task 3: Lambda expressions

Pass a lambda expression as an argument to method, which will call the given function with a parameter.


#include <iostream>

void x_100(bool (*fun)(int)) {
    std::cout << fun(100) << std::endl;
}

int main()
{
    x_100([](int a) { return a % 2 == 0; });
}
Task 4: Polynomials

Write a method, that will read functions parameters from a file and will create an array of pointers to polynomial functions.

If you want use lambda expressions, you should take care about using "=" symbol inside of square brackets