Answer the question
In order to leave comments, you need to log in
What is the most convenient (compact) way in C++ to assign two variables by calling a function once?
In Python I have for example:
def func(a, b):
return (a, b)
(x, y) = func(1, 2) # x = 1, y = 2
int *func(int a, int b) {
int res[2];
res[0] = a;
res[1] = b;
return res;
}
// способ 1 (но мне нельзя вызывать функцию 2 раза!)
x = func(1, 2)[0];
y = func(1, 2)[1];
// способ 2
int *a = func(1, 2);
x = a[0];
y = a[1];
// 3 строки писать для такой фигни?!
Answer the question
In order to leave comments, you need to log in
First, your code is wrong.
The res array is local to the func function, and using a pointer to it after the function returns is undefined behavior. You're just lucky that the code works.
As for solutions - the closest thing to python code is to use std::tie (introduced in C++11):
std::pair<int, int> func()
{
return std::make_pair(1, 2);
}
int x, y;
std::tie(x, y) = func();
void func(int &res1, int & res2)
{
res1 = 1;
res2 = 2;
}
int x, y;
func(x, y);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question