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

Your First Function: void, Declarations, and Definitions

Your addition program works, but everything is crammed into main. Real programs are split into smaller, named pieces called functions, and you have been using them all along: printf and scanf are functions someone else wrote. In this lesson you write your own, a function that greets the user. Then you break it in two different ways to find out what the compiler needs to know about a function before you can use it.

In this lesson you will

  • Write and call a void function with no parameters
  • Follow the flow of execution into a function and back out
  • Tell the difference between a function declaration (prototype) and a definition
  • Read the “implicit declaration” and “conflicting types” errors

Start by copying your project, as you did in the scanf lesson: copy 002-UserInputCProgram to a new folder named 003-FunctionDemoCProgram, save the project under the new name, and update its title and output filename.

Try it: write a function and call it

Above main, type a new function called WelcomeMessage. Inside main, add one line, WelcomeMessage();, before everything else:

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

void WelcomeMessage(void)
{
    printf("Welcome to the addition program\n");
    printf("I hope you enjoy this program\n\n");
}

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 sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Build and run, and enter 15 and 16:

Welcome to the addition program
I hope you enjoy this program

Please enter a value for x:
15
Please enter a value for y:
16
The sum of 15.00 and 16.00 is 31.00

Every C program starts running at the first line of main. When it reaches WelcomeMessage();, execution jumps to the first line inside WelcomeMessage, runs its two printf lines, and then returns to main, carrying on from the line after the call. See it for yourself with the debugger from the previous lesson. Put a breakpoint on the call, start debugging, and choose Step into: the yellow arrow moves inside your function. Choose Next line instead, and the whole function runs in one step.

What just happened

A function has a return type, a name, a list of parameters in brackets, and a body in curly braces:

  • void is the return type. void means “nothing”: this function does its job (printing) and hands no value back.
  • WelcomeMessage is the name. Choose names that say what the function does, so that main reads almost like a description of the program.
  • (void) in the brackets says the function takes no parameters. (You will also see empty brackets (), as in int main(). In the newest C standard they mean the same thing, but (void) is the clearest way to say “no parameters”.)
  • The braces hold the statements that run each time the function is called.

In this series, braces go on their own lines, and function names use upper camel case (WelcomeMessage). Many programmers put the opening brace at the end of the first line instead. Either style is fine, as long as you are consistent.

Try it: move the function below main

Many programmers like main to be the first thing in the file, so that a reader sees the big picture first. Cut the whole WelcomeMessage function and paste it below main, then build.

Break it on purpose: call a function the compiler has not seen yet

Observe: the build fails. With GCC 14 the first message is:

main.c:6:5: error: implicit declaration of function 'WelcomeMessage' [-Wimplicit-function-declaration]

Older compilers, such as the GCC included with many Code::Blocks installs, may report this as a warning instead, often followed by an error saying conflicting types for 'WelcomeMessage'. Either way, the program does not build cleanly.

Remember that the compiler reads from top to bottom. When it reaches the call in main, it has never heard of WelcomeMessage, so it does not know what kind of function this is.

The fix is to announce the function before main. Add this one line, ending in a semicolon, above main:

void WelcomeMessage(void);
#include <stdio.h>
#include <stdlib.h>

void WelcomeMessage(void);

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 sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

void WelcomeMessage(void)
{
    printf("Welcome to the addition program\n");
    printf("I hope you enjoy this program\n\n");
}

Build and run: it works again, with the function below main.

Name it: declaration vs definition

  • void WelcomeMessage(void); is a function declaration, also called a prototype. It gives the function’s return type, name and parameters, and ends with a semicolon. It promises the compiler that the function exists.
  • The version with a body in braces is the function definition. It is the actual code that runs.
  • It is just like variables: float x; declares a name and a type. A function prototype does the same for a function.

Break it on purpose: break the promise

Change the definition (not the prototype) so that it takes a parameter: void WelcomeMessage(int times). Leave the prototype as void WelcomeMessage(void); and build:

main.c:23:6: error: conflicting types for 'WelcomeMessage'; have 'void(int)'
main.c:4:6: note: previous declaration of 'WelcomeMessage' with type 'void(void)'

The prototype and the definition must match exactly: same return type, same name, same parameter types. The compiler even tells you where the earlier promise was made (line 4). Undo the change and build again. Code::Blocks shows similar messages in its build log.

Key terms

  • Function: a named block of code that performs a task and can be called from elsewhere.
  • Call: using a function by writing its name followed by brackets, e.g. WelcomeMessage();
  • Return type: the type of value a function hands back. void means none.
  • Parameters: the inputs a function accepts, listed in its brackets.
  • Declaration (prototype): the function’s header followed by a semicolon. It tells the compiler the function exists.
  • Definition: the function’s header plus its body. It is the code that actually runs.
  • Flow of execution: the order in which statements run, including jumps into functions and back.

Quick check

  1. Where does every C program start running?

    Show answer

    At the first statement inside main.

  2. What does void mean as a return type?

    Show answer

    The function does not return a value. It just does its job, such as printing.

  3. Your function is defined below main and the build reports “implicit declaration of function”. What should you add?

    Show answer

    A prototype above main, for example void WelcomeMessage(void);

  4. Which line is a prototype: void Hello(void); or void Hello(void) { printf("Hi\n"); }?

    Show answer

    void Hello(void);. It has no body and ends with a semicolon. The other line is a definition.

Optional: a recorded demonstration of these steps starts around 9:10.

Part of the Introduction to C series. Next: Functions That Return Values, and Variable Scope

Introduction to functions

0008.1

Required reading: C functions (This is a link to an external website)

Exercise

Similar to our previous example, create a program which contains:

  1. A function which returns the area of a circle given its radius (assume all variables used are double)
  2. A Function which returns the volume of a circle given the radius(assume all variables used are double)
  3. A function which does not return any data and takes no parameters but outputs the author of your program .  Name your function Signature.

Solution

Note the function declarations.  This is necessary for proper execution of our code.

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

//global variables
double area,volume;
double radius;
const double PI = 3.14;

//function declarations
double Area(double radius);
double Volume(double radius);
void Signature();

int main()
{
    //initialization
    area,radius,volume = -999;

    printf("enter radius\n");
    scanf("%lf", &radius);

    area    =   Area(radius);
    volume  =   Volume(radius);

    printf("The  Area is \t: \t%.2f\n",area);
    printf("The  Volume is \t: \t%.2f\n",volume);

    Signature();



}

double Volume(double radius)
{
    return((4/3)*PI*radius*radius*radius);
}

double Area(double radius)
{
    return (PI*radius*radius);
}

void Signature()
{
	//ASCII Art Generated using https://patorjk.com/software/taag/#p=testall&f=Big&t=kunge
    printf("Thanks for using my program!  \n");
    printf("  _  __                       \n");
    printf(" | |/ /                       \n");
    printf(" | ' /_   _ _ __   __ _  ___  \n");
    printf(" |  <| | | | '_ \ / _` |/ _ \ \n");
    printf(" | . \.|_| | | | | (_| |  __/ \n");
    printf(" |_|\_\__,_|_| |_|\__, |\___| \n");
    printf("                   __/ |      \n");
    printf("                  |___/       \n");
    printf("Author: Vedesh Kungebeharry   \n");
    printf("contact: VKunge@gmail.com     \n");
    printf("exiting...  \n");


}

© 2020  Vedesh Kungebeharry. All rights reserved. 

Formulas and Functions – Part 2 (Video)

This series of videos is a continuation of the post, Formulas and Functions – Part 1 (Class Video)

Use this file and follow along with the videos, pausing the video when you need to accomplish a task:

It 5 videos covering the following functions: Max, Min, Count, Countif, Rank, and Vlookup.

A 6th function, PMT was left for your research and homework.

See the videos below, and follow the instructions for homework based on the pmt function:

Max and Min

Count

Countif

Rank

Vlookup

PMT

Homework – Research/examine the PMT function.

Explain :

  1. The functions’ parameters.
  2. The purpose of the function.

We will be discussing this function at our next class.

© 2020  Vedesh Kungebeharry. All rights reserved.