John Phung said:
How do you pass a data structure into a function? I'm using c++ to solve the
producer and consumer problem and so far, I cannot find an example of how to do
this. So, if anyone can help me, that would be nice.
#include <iostream>
// define a structure
struct X
{
int m;
};
// a function with a structure as a parameter
void function(X arg)
{
std::cout << arg.m << '\n'; // prints 42
}
int main()
{
X obj = {42}; // create an instance of type 'X'
function(obj); // pass 'X' to 'function()'
return 0;
}
If the structure is 'large', it's usually better to
pass by reference:
void function(X& arg)
{
// etc
}
And if the function doesn't modify the argument, pass
by const reference:
void function(const X& arg)
{
// etc
}
In all cases above, the calling syntax is the same.
Another way is by using a pointer parameter, which
does change the calling syntax:
void function (X *arg) // or const X *arg if applicable
{
// etc
}
call with:
X obj = {42};
function(&obj);
Which C++ book(s) are you reading?
-Mike