The code below is passing the struct variable:
struct someStruct {
unsigned int total;
};
int test(struct someStruct* state) {
state->total = 4;
}
int main () {
struct someStruct s;
s.total = 5;
test(&s);
printf("\ns.total = %d\n", s.total);
}
(The source from Pass struct by reference in C
)
While programming in C++ may I pass this structure without &? I mean
test(s); // or should test(&s);
Will s be copied if I do that?
In C++ you can make the function take a reference as parameter:
You can call the function like that:
No copy will be made. Inside the function,
statewill behave like it wass. Note that thestructkeyword is only required when declaring the struct in C++. Also, in C++ your printing code should look like this:You have to include
iostreamfor that to work.