Functions That Return Values, and Variable Scope

Your WelcomeMessage function does something, but it does not give back anything. Most useful functions take some input, process it, and hand back a result. That is the input–process–output pattern you will use in every program. In this lesson you write a function that adds two numbers and returns the answer. Then you find out what main can and cannot see inside it.

In this lesson you will

  • Write a function with parameters and a return value
  • Refactor main to call it
  • Discover local scope: why main cannot see a function’s variables
  • Use a naming convention to tell local and global names apart

Try it: a function that returns a value

Continue in your 003-FunctionDemoCProgram project. Below WelcomeMessage, add a second function:

float TheSumOfTwoNumbers(float theFirstNumber, float theSecondNumber)
{
    float result;
    result = theFirstNumber + theSecondNumber;
    return result;
}
  • The return type is float, not void. This function promises to hand back a float.
  • (float theFirstNumber, float theSecondNumber) are its parameters, the inputs it needs. Each parameter has a type and a name, separated by commas.
  • Inside, it creates a variable result to hold the output, works it out, and hands it back with return result;
  • The name is long on purpose. TheSumOfTwoNumbers describes exactly what the function gives you, so code that uses it reads like a sentence. This is called self-documenting code.

Add its prototype above main, next to the one for WelcomeMessage. Then build once, to check there are no errors before you go on.

Try it: refactor main

Now change main to use the new function instead of adding the numbers itself. Replace the float sum = x + y; line, and rename the variable to theAnswer so that it is clearly different from the function’s own result. Here is the whole program:

#include <stdio.h>
#include <stdlib.h>

void WelcomeMessage(void);
float TheSumOfTwoNumbers(float theFirstNumber, float theSecondNumber);

int main()
{
    WelcomeMessage();

    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &y);

    float theAnswer = TheSumOfTwoNumbers(x, y);
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, theAnswer);
    return 0;
}

void WelcomeMessage(void)
{
    printf("Welcome to the addition program\n\n");
}

float TheSumOfTwoNumbers(float theFirstNumber, float theSecondNumber)
{
    float result;
    result = theFirstNumber + theSecondNumber;
    return result;
}

Break it on purpose: rename a variable, but not everywhere

Suppose you change float sum = … to float theAnswer = … but forget to update the printf line, which still ends x, y, sum);. Build it:

main.c:20:56: error: 'sum' undeclared (first use in this function)

sum no longer exists. Changing the structure or names in your code without changing what it does is called refactoring. When you rename something, you must change every place it is used. Code::Blocks shows a similar error in its build log. Fix the printf and build again.

Build and run, and enter 11 twice:

Welcome to the addition program

Please enter a value for x:
11
Please enter a value for y:
11
The sum of 11.00 and 11.00 is 22.00

What just happened

When main reaches TheSumOfTwoNumbers(x, y), the values of x and y are copied into the parameters: theFirstNumber receives 11, and theSecondNumber receives 11. The function adds them and stores 22 in result. return result; then sends that value back to the caller, where it takes the place of the function call. So the line in main becomes, in effect, float theAnswer = 22;

You could shorten the function to the single line return theFirstNumber + theSecondNumber;, and it would work just the same. In this series, though, you will set up a variable to hold the output, fill it, and return it. When functions grow longer and more complicated, a clearly named result variable makes the code far easier for someone else, or for you months later, to read and to check in the Watches window.

Try it: reach inside the function

Break it on purpose: use a function’s variable in main

The function worked out result, so surely main can print it? Add this line in main, just after the call: printf("Test: %f\n", result);. As you type, notice that Code::Blocks does not suggest result in its autocomplete list, which is a clue. Build:

main.c:20:26: error: 'result' undeclared (first use in this function)

From main‘s point of view, there is no such variable. Delete the line and build again.

Name it: scope

A variable declared inside a function (including its parameters) is a local variable. It exists only while that function is running, and it can only be used inside that function. This is called its scope. result, theFirstNumber and theSecondNumber are local to TheSumOfTwoNumbers. In the same way, x, y and theAnswer are local to main, and the function cannot see them either. That is why values travel in through parameters and out through return.

A variable declared outside every function, near the top of the file, is a global variable. Every function in the file can use it:

#include <stdio.h>
#include <stdlib.h>

float TheAnswer = 15;

void ShowTheAnswer(void);

int main()
{
    printf("Test: %.2f\n", TheAnswer);
    ShowTheAnswer();
    return 0;
}

void ShowTheAnswer(void)
{
    printf("Also visible here: %.2f\n", TheAnswer);
}
Test: 15.00
Also visible here: 15.00

Globals are handy, but use them sparingly. Any function can change a global, so when its value is wrong, the mistake could be anywhere in the file. Parameters and return values keep each function’s inputs and outputs out in the open.

A naming convention to help you. C itself does not care how you capitalise names, but a consistent style tells the reader what kind of name they are looking at. This series uses upper camel case (PascalCase) for functions and globals, as in TheSumOfTwoNumbers and TheAnswer, and lower camel case (camelCase) for local variables and parameters, as in theAnswer and theFirstNumber. You can tell at a glance that TheAnswer is global and theAnswer is local. The convention helps you. The compiler only sees two different names.

Key terms

  • Parameter: a variable in a function’s brackets that receives a value when the function is called.
  • Argument: the actual value passed in a call, e.g. x and y in TheSumOfTwoNumbers(x, y).
  • Return value: the value a function sends back to its caller with return.
  • Caller: the code that called the function.
  • Refactoring: restructuring or renaming code without changing what it does.
  • Scope: the part of a program where a name can be used.
  • Local variable: declared inside a function, and only usable there.
  • Global variable: declared outside all functions, and usable by every function in the file.

Quick check

  1. What does TheSumOfTwoNumbers(2.5, 4) return?

    Show answer

    6.5, as a float.

  2. Why can main not print result directly?

    Show answer

    result is local to TheSumOfTwoNumbers. It only exists inside that function, so main must use the returned value instead.

  3. You rename total to grandTotal and the build reports 'total' undeclared. What happened?

    Show answer

    At least one place still uses the old name. When refactoring, update every use of the name.

  4. Under this series’ naming convention, which is probably global: MaxScore or maxScore?

    Show answer

    MaxScore (upper camel case). maxScore would be a local variable or parameter.

Optional: a recorded demonstration of these steps starts around 25:00. Scope and global variables are covered from about 45:45.

Part of the Introduction to C series. Next: Using Library Functions: #include, getch(), and the Input Buffer