How to return struct from a function in C++

3 Answers

0 votes
#include <iostream>

struct ST {
    int first, second, third;
} typedef ST;
 
ST get_struct_value() {
    ST st;
     
    st.first = 123;
    st.second = 87;
    st.third = 3;
     
    return st;
}
 
int main() {
    auto st = get_struct_value();
    
    std::cout << st.first << " " << st.second << " " << st.third;
}
 
 
 
 
/*
run:
 
123 87 3
 
*/

 



answered May 14, 2021 by avibootz
edited Dec 8, 2023 by avibootz
0 votes
#include <iostream>

struct ST {
	int x, y;
};

ST get_struct_value(const int n) {
	return {n, n * 3};
}


int main(void)
{
   	auto [x, y] = get_struct_value(5);

    std::cout << x << ' ' << y;
}
 
 
 
 
/*
run:
 
5 15
 
*/

 



answered Dec 8, 2023 by avibootz
0 votes
#include <iostream>

struct ST {
    int first, second, third;
} typedef ST;
 
ST get_struct_value() {
    ST st;
     
    st.first = 123;
    st.second = 87;
    st.third = 3;
     
    return st;
}
 
int main() {
    auto [x, y, z] = get_struct_value();
 
    std::cout << x << ' ' << y << ' ' << z;
}
 
 
 
 
/*
run:
 
123 87 3
 
*/

 



answered Dec 8, 2023 by avibootz

Related questions

1 answer 177 views
1 answer 215 views
1 answer 337 views
1 answer 273 views
1 answer 180 views
180 views asked Oct 25, 2022 by avibootz
1 answer 110 views
1 answer 130 views
...