Structures and Functions in C Programming Language

Of course a sensible alternative to writing out the addition each time is to define a function to do the same job - but this raises the question of passing structures as parameters. Fortunately this isn't a big problem. Most C compilers, will allow you to pass entire structures as parameters and return entire structures. As with all C parameters structures are passed by value and so if you want to allow a function to alter a parameter you have to remember to pass a pointer to a struct. Given that you can pass and return structs the function is fairly easy:

struct comp add(struct comp a , struct comp b)

{

struct comp c;

c.real=a.real+b.real;

c.imag=a.imag+ b.imag;

return c;

}

After you have defined the add function you can write a complex addition as:

x=add(y,z)

which isn't too far from the x=y+z that you would really like to use. Finally notice that passing a struct by value might use up rather a lot of memory as a complete copy of the structure is made for the function.


Learn More :