Join Isac Artzi for an in-depth discussion in this video Returning data from functions, part of C Essential Training.
- In this video, we're going to continue our discussion on functions, and we will learn even more powerful features and many ways that can make our coding experience more fun, more efficient, and more powerful. Let's look at one feature of the functions called return value. It is possible for a function to either return a value, or not return one. What does it mean? It means that if we want to specify a specific type of value, we will assign the data type to the function and then we'll put that function in such a way that it returns a very specific data type to match the one that's been declared in the function header.
If no result needs to be returned, then the function data type is void. For example, if no result is returned, the data type of the function is void addNumbers. In this case, the function simply computes something inside its body, and then prints the result. In this example, a result is returned, in addition to receiving arguments for its two parameters. In this case, the function returns a float, and the float is then capture into an external variable called theResult = addNumbers.
This line means that whatever the function computes, it's going to be forwarded to a variable outside the function, and then being used in the rest of the program. Let's see how this works in code. To demonstrate this, I created a fairly length scenario in which we will look at the ability to calculate statistical data in a basketball game. Or, more correctly said, an imaginary basketball game. This program describes a very simplistic approach to gathering statistics.
We are going to ask the user to enter the number of shots in each quarter, the number of three-point shots, and the number of two-point shots in every quarter. And we are now going through a lengthy printf and scanf pairs of commands so that we can capture all this data from the user. We're going to scroll down now to the actual execution. As you can see, there are numerous functions culled, starting with line 68 all the way through 76. Let's look at line 68 for example.
I'm declaring a variable totalPoints, which is going to be storing the result returned by a function, calculateTotalPointsMade, to which I am going to pass four variables as arguments, total shots in Q1, in Q2, Q3, and Q4. Notice that in the subsequent two lines, lines 69 and 70, I am capturing data for two additional type of statistics, the total two points made, and the total three points.
However, I am using the same exact function. Why? Let's see. calculateTotalPointsMade is a function that receives four values with arguments because it has been defined with four parameters in line 83, int Q1, int Q2, Q3, and Q4, and it returns a value that is also an integer.
Now notice something interesting which I did on purpose. Inside the function, there is a variable called sum that is defined as double. Even though the numbers that are added are int, the function is expected to return an int value even though sum is double. In the process of returning that value, the C compiler is automatically converting the value of sum from double into an int.
I did that deliberately so you can see that that's possible. Sometimes, it will be incorrect to do so, but again, as I said before, the C compiler assume you know what you're doing. If the result in this case, because it's double, would be, let's say, 20.0, the int version of it will be 20. However, if the result would have been 20.5, we would have lost that .5. Let's continue with assessing what this program does.
Line 72 through 74 calculates various averages and performances. For example, line 72 calculates the average performance per quarter. It's a function that receives four arguments, add them, divides them by four, and produces an average calculation. Let's see what happens now when we calculate performance. There's another interesting notation. If you look at line 94, float performance equal shots made divided by total shots times 100, notice float type in parentheses to the left of shots made and to the left of total shots.
The reason for this is shots made and total shots are integers, we need to insure that when we are dividing two integers, the result is float. This operation is called type casting. We are forcing shots made to become a float, even though it's an int. So internally, we can look at it as just adding a dot point zero, it doesn't change the value, but it now becomes a float. If you don't do that, your performance will be zero, because all those variables will become integers, and you're welcome to try this and see what happens.
Now that we have all this in place, let's just test the program and see what it does, and after the video is over, please download the file and experiment on your own and see if you can find ways to make this better. Let's enter the shots for the first quarter, let's say 20 shots. 2-point shots made, five. 3-point shots made, two. Second quarter. I'm going to enter 18, four, four, 12 shots, five, two, and 16 shots, 8 and then 2.
And here are our statistics. Total attempts made, 66. Total 2-points shots made, 22, 3-points, 10, and so on, success for two, for three and average points per quarter. Again, this is not the most accurate, the best basketball statistics out there by all means. However, its purpose was to illustrate a few things. First, the convenience of using functional programming, the convenience of having return values, and the ability to repeat codes to one function.
In the upcoming videos, we will continue our discussions with functions, functional programming, parameters, and so on, and you will be learning how you can make C work for you in a much, much more efficient way.
C is a great first step for new programmers, and a way to broaden and deepen your knowledge if you've already programmed for a while. Press Play to start learning.
- Reviewing the C language and the C11 standard
- Understanding the development cycle
- Setting values
- Writing statements and expressions
- Adding comments to code for clarity
- Declaring data types
- Manipulating strings
- Declaring variables
- Using operators and expressions
- Working with functions
- Controlling flow with if-else statements and loops
- Initializing arrays
- Working with files
- Including files and executing macros with the C preprocessor
- Understanding best coding practices
Skill Level Beginner
Q: How do I configure a C compiler in Windows?
<div>To configure a C compiler for Eclipse in Windows, follow these steps: </div><div>1) Download the MinGW installer from <a target="_blank" href="http://sourceforge.net/projects/mingw/files/latest/download?source=files">http://sourceforge.net/projects/mingw/files/latest/download?source=files.</a> </div><div>2) Open the resulting mingw-get-setup.exe file and click <strong>Continue</strong> until you get to the Installation Manager. </div><div>3) Select mingw32-base and choose <strong>Mark for Installation</strong>. </div><div>4) Under the <strong>Installation</strong> menu, choose <strong>Apply Changes </strong>and then <strong>Apply</strong>. Wait for the process to complete. </div><div>5) Open Eclipse and navigate to the <strong>Preferences</strong> option under the <strong>Window</strong> menu. </div><div>6) Under <strong>C/C++</strong>, find the <strong>New C/C++ Project Wizard</strong> option. For the <strong>Hello World ANSI C Project</strong> option, choose the <strong>MinGW GCC</strong> toolchain, and click <strong>Make toolchain(s) preferred</strong>. Press <strong>OK</strong>. </div><div>7) To create a new project, select the <strong>File</strong> menu and choose <strong>New C Project</strong>. </div><div> 8) In the <strong>Project Type</strong> area, choose <strong>Hello World ANSI C Project</strong>, and specify a project name. Press <strong>Finish</strong>. This will create a .c file inside a folder named “src.” </div><div>9) Open the exercise file and copy and paste the contents into the .c file created inside of your project, replacing the contents. </div>
Q: How do I use the exercise files on a Windows machine?
A: On Windows, the exercise files require a change to the compiler settings to enable C99 support. To change the compiler settings, follow these steps:<br /><br /> 1) Right-click on the .c file and choose <strong>Properties</strong>.<br /> 2) Under <strong>C/C++ Build</strong> and <strong>Settings</strong>, change the <strong>Command</strong> value to
“gcc -std=c99”. Click OK.