C Structure and Function

Similar to variables of built-in types, you can also pass structure variables to a function.


Passing structs to functions

We recommended you to learn these tutorials before you learn how to pass structs to functions.

Here's how you can pass structures to a function

Output

Enter name: Bond
Enter age: 13

Displaying information
Name: Bond
Age: 13  

Here, a struct variable s1 of type struct student is created. The variable is passed to the display() function using display(s1); statement.


Return struct from a function

Here's how you can return structure from a function:

Here, the getInformation() function is called using s = getInformation(); statement. The function returns a structure of type struct student. The returned structure is displayed from the main() function.

Notice that, the return type of getInformation() is also struct student.


Passing struct by reference

You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed.

During pass by reference, the memory addresses of struct variables are passed to the function.

Output

For first number,
Enter real part:  1.1
Enter imaginary part:  -2.4
For second number, 
Enter real part:  3.4
Enter imaginary part:  -3.2

result.real = 4.5
result.imag = -5.6  

In the above program, three structure variables c1, c2 and the address of result is passed to the addNumbers() function. Here, result is passed by reference.

When the result variable inside the addNumbers() is altered, the result variable inside the main() function is also altered accordingly.