You are referring to this code:
#include <iostream>
#include <vector>
std::vector<int> first_three_multiples(int num) {
std::vector<int> multiples{num, num * 2, num * 3};
return multiples;
}
int main() {
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}
In the line of code you mentioned, multiples
isn’t a function. It is neither a function declaration nor a call to a function. Instead two things are being done in a single statement. A variable is being declared AND it is being initialized in a single statement.
Suppose you want to assign an integer to some variable. You can do so in two steps or you could do it in a single step.
// In two steps
int i; // Declaring a variable
i = 2; // Assigning a value to the variable
// In a single step
int i = 2; // Declaring and initializing done in one step
The same thing is being done in the line of code you mentioned. multiples isn’t a function. It is a variable which is meant to store a vector of integers.
std::vector<int> multiples{num, num * 2, num * 3};
is a way of declaring and initializing the variable.
An equivalent alternative to do the same is std::vector<int> multiples = {num, num * 2, num * 3};
num
is the parameter of the function first_three_multiples
. From our main function, we call the function with an argument such as first_three_multiples(8)
. The argument 8 gets assigned to the parameter num
of the first_three_multiples
function. Within our function, we declare a variable called multiples
and also initialize the vector with three elements (in a single step).
In our main function, we make the call first_three_multiples(8). The function returns a vector consisting of three elements.
If we try to print the vector directly e.g. std::cout << first_three_multiples(8);
we will get an error.
The loop in main is meant to iterate over the vector and print each element of the vector on a separate line.