How to pass struct to function by reference in C++

1 Answer

0 votes
#include <iostream>
#include <string>
 
using std::cout;
using std::endl;
using std::string;
 
struct user {
    string name;
    int age;
};
 
void print(user u) {
    cout << u.name << " " << u.age << endl;
}
 
void set(user &u) { // by ref
    u.age = 98;
}
 
int main()
{
    user u = { "tom", 54 };
     
    print(u);
 
    set(u);
 
    print(u);
}


 
/*
run:
 
tom 54
tom 98
 
*/

 



answered May 24, 2018 by avibootz
edited Jun 13, 2024 by avibootz

Related questions

1 answer 116 views
1 answer 197 views
1 answer 87 views
87 views asked Dec 19, 2024 by avibootz
2 answers 154 views
154 views asked Aug 22, 2022 by avibootz
...