Friday, October 1, 2010

Passing Entire Structures to Functions in C,C++

When a structure is used as an argument to a function, the entire structure is passed
using the standard call-by-value method. Of course, this means that any changes 

made to the contents of the structure inside the function to which it is passed do not
affect the structure used as an argument.
When using a structure as a parameter, remember that the type of the argument
must match the type of the parameter. For example, in the following program both the
argument arg and the parameter parm are declared as the same type of structure.
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
} ;
void f1(struct struct_type parm);
int main(void)
{
struct struct_type arg;
arg.a = 1000;
f1(arg);
return 0;
}
void f1(struct struct_type parm)
{
printf("%d", parm.a);
}
As this program illustrates, if you will be declaring parameters that are structures,
you must make the declaration of the structure type global so that all parts of your
program can use it. For example, had struct_type been declared inside main() (for
example), then it would not have been visible to f1().
As just stated, when passing structures, the type of the argument must match
the type of the parameter. It is not sufficient for them to simply be physically similar;
their type names must match. For example, the following version of the preceding
program is incorrect and will not compile because the type name of the argument
used to call f1() differs from the type name of its parameter.

/* This program is incorrect and will not compile. */
#include <stdio.h>
/* Define a structure type. */
struct struct_type {
int a, b;
char ch;
} ;
/* Define a structure similar to struct_type,
but with a different name. */
struct struct_type2 {
int a, b;
char ch;
} ;
void f1(struct struct_type2 parm);
int main(void)
{
struct struct_type arg;
arg.a = 1000;
f1(arg); /* type mismatch */
return 0;
}
void f1(struct struct_type2 parm)
{
printf("%d", parm.a);

No comments:

Post a Comment