In the next video we’ll learn how to pass structures to functions by value.
Passing by value means that a copy will be made of the data stored in the structure. We will therefore have access to all of the data stored in the structure variable but we cannot modify it within the function (since all we’d end up doing is modify the copies of the values).
Investigate25.10.
Imagine we declare a structure named student in both the main() function and in a new function, and we then pass the structure from the main() function into our new one by value. If we now change a value within the new function’s structure, will it affect the original structure?
This stores student data (first and last name, birth year and average grade) in a structure.
The following Codecast shows you how to pass a student record to a function in order to print the record. Note that in the video we do not use typedef for the sole reason that sadly, typedef has not (yet) been implemented in the recording software.
If you cannot see this codecast, please click here.
Check Your UnderstandingCheck Your Understanding
1.
Suppose you have declared a structure to hold student data as in the video:
Suppose furthermore that you are writing a function compareStudents(), to which you’d like to pass two students of type struct student, and which returns the average grade of the student whose average grade is the lower of the two. Which of the following is the correct function prototype for such a function?
and are writing a function compareStudents() which compares the average grades of the two student records passed to the function, which of the following correctly finds the lower of the two average grades:
If we want to be able to modify a structure variable from within a function we need to pass a pointer to this variable to the function - just as we do for regular variables. In other words, we need to pass the variable to the function "by reference". In the next video we’ll learn how to do so.
If you cannot see this codecast, please click here.
Check Your UnderstandingCheck Your Understanding
1.
What is wrong with the following piece of code and how would you fix it?