topskill.dev
CoursesTracks
All courses/C Programming for BeginnersFollow a Function Call and Its Return Value
Functions and Return Values
2 / 6
← C Programming for Beginners
○What a program actually does○The computer and the operating system○From a C file to a running program○Compiled and interpreted programs○Trace One Tiny C Program○Print the Opening Sign✦Module Quiz
○Your First C Program○Variables and Formatted Output○Arithmetic and Integer Division○Formatting and Numeric Conversion○Calculate a Shop Total✦Module Quiz
○Declare and initialize variables○Label the parts bin○Assign a new value○Update the checkout board○Choose int, double, and char○Write a battery test label○Keep local names and constants clear○Count free kit slots✦Module Quiz
○Match printf placeholders and arguments○Print a radio test slip○Build lines with escapes and multiple calls○Print a clock pickup note○Print percent signs and aligned values○Line up a cleaning report○Evaluate expressions before printing○Divide reflectors among trays✦Module Quiz
○Comparisons and True or False○How if and else Choose a Path○Choose a Ticket Message○Select a Fixed Choice with switch○Choose a Service Desk✦Module Quiz
○For Loops: Repeat a Known Number of Times○Add Daily Contributions○While Loops: Repeat While a Condition Holds○Make a Countdown○Run Once with do while○Label a Two-Row Shelf○Label Tool Drawers✦Module Quiz
○Define and Call a Function●Follow a Function Call and Its Return Value○Return a Square○Declare Before a Function Call○Declare and Convert✦Module Quiz
○Arrays and Zero-Based Indexes○Add Array Elements○Count Array Slots Safely○Average Workshop Ratings○Rows and Columns in Memory○Total a Two-Row Grid✦Module Quiz
○C Strings and the Null Terminator○Count a Label○Compare Complete Strings○Verify a Pickup Code○Visit Each Character○Count a Letter in a Label✦Module Quiz
○Pointers: Addresses and Dereferencing○Update Through a Pointer○Pass an Address to a Function○Swap Two Counts○Array Addresses and Offsets○Total with an In-Bounds Pointer○Null, Validity, and Lifetime○Handle an Optional Pointer✦Module Quiz
○Pass an Array and Its Length○Total Readings in a Function○Change Array Elements Through a Parameter○Update Each Stock Count✦Module Quiz
○Define a Supply Record○Record Thread Supplies○Update a Record Member○Update the Paper Stock○Walk an Array of Records○Total the Flyer Stacks○Pass a Record to a Function○Print a Badge Record✦Module Quiz
○One Value in Shared Storage○Record One Ticket Value○A Tag Tells You What Is Stored○Read a Tagged Repair Ticket○Compare Union and Struct Storage○Choose the Right Storage✦Module Quiz
○Read Bits with AND○Check an Equipment Flag○Turn a Flag On with OR○Mark a Kit Ready○Toggle and Clear Individual Flags○Toggle a Warning Flag○Move a Bit into Position○Build a Position Mask✦Module Quiz
○Include the Right Header○Measure a Label with strlen○Guard a Macro Default○Set a Fallback Badge Limit○Include Code Only for Debug Builds○Show an Inventory Diagnostic When Enabled○Parenthesize a Simple Macro○Keep a Macro Calculation Grouped✦Module Quiz
○Name a Status with enum○Confirm an Application Status○Alias a Record Type with typedef○Initialize a Ribbon Record✦Module Quiz
○Where the storage comes from○Request and Release an Array○Store Three Repair Counts○Start Allocated Counters at Zero○Start Station Counters at Zero○Allocate and Release Records○Allocate the parts report✦Module Quiz
○Print a Formatted Label○Print the carving sign○Print Characters with putchar○Build a two-letter mark○Format into a Bounded Buffer○Prepare the shelf label○Write a Line to stdout with fputs○Post the ready notice○Input and Diagnostics in a Local Terminal✦Module Quiz

Follow a Function Call and Its Return Value

Follow a call out and back

announce did its work by printing. A calculation helper can instead return a number for its caller to use. The returned value completes the waiting expression; the caller can store it, calculate with it, or print it.

A function call temporarily hands control to another function. The caller is the function making the call; the callee is the one being called. Returning ends that one invocation (one particular call), then resumes the caller at the place waiting for it. It does not restart main.

Here main asks double_points for a result. The argument value 4 is copied into the parameter points; doubled becomes 8. return doubled; sends the value 8 back, so main can finish initializing result.

c
#include <stdio.h>

int double_points(int points) {
    int doubled = points * 2;
    return doubled;
}

int main(void) {
    int result = double_points(4);
    printf("Result: %d\n", result);
    return 0;
}

The output is Result: 8. Returning a number does not display it: printf does that. return 0; in main reports successful completion to the environment that ran the program.

A helper can call another helper

This time a workshop bill includes a fee and then gets doubled for two bookings. Read from main, not from the first function definition. The letter comments mark places in the trace below.

c
#include <stdio.h>

int add_fee(int amount) {
    int fee = 2;
    amount = amount + fee;        /* C */
    return amount;               /* D */
}

int booking_total(int price) {
    int with_fee = add_fee(price); /* B: wait here for a value */
    int total = with_fee * 2;      /* E */
    return total;                 /* F */
}

int main(void) {
    int price = 5;
    int bill = booking_total(price); /* A: wait here for a value */
    printf("Price: %d, bill: %d\n", price, bill); /* G */
    return 0;
}
StepRunning functionWhat happens next
AmainCopy 5 into booking_total's parameter price. main waits to finish initializing bill.
Bbooking_totalCopy its price value, 5, into add_fee's parameter amount. Wait to finish initializing with_fee.
Cadd_feeIts local fee is 2. Its own amount changes from 5 to 7. Both callers' price variables stay 5.
Dadd_feeReturn 7 to B. This invocation ends; its parameter and local variable no longer live.
Ebooking_totalB completes with with_fee = 7. Execution continues with total = 14.
Fbooking_totalReturn 14 to A. This invocation's parameters and locals no longer live.
GmainA completes with bill = 14. Print Price: 5, bill: 14, then return from main.

Keep track with a call stack

A stack is a last-in, first-out arrangement: the most recently called function finishes before the waiting caller resumes. Each box below is a frame, a record for one invocation. We draw its parameters, local values, and return point so you can follow what is still needed.

Read the snapshots in numbered order. The uppermost frame is running; lower frames are waiting, not finished. At snapshot 3, all three calls are still active. At snapshot 4, add_fee has ended, but main is still waiting for booking_total. A pending initializer is not a usable value: do not read bill or with_fee before its call has supplied the result.

This is a conceptual call stack, not a picture of measured memory addresses. A machine stack is a common implementation, but C does not require every parameter or local variable to occupy a literal stack slot. A compiler may keep values in registers or inline a helper (replace a call with equivalent work). Those optimizations do not change the observable result of this defined program.

A name's scope is not an object's lifetime

Scope tells you where a name can be used in source code. amount can be named inside add_fee, not inside main. The two variables named price belong to different functions; their spelling does not make them one object.

An object is storage holding a value, such as a variable. Lifetime tells you when an object exists during execution. These ordinary local variables have automatic storage duration. While a helper runs, the waiting caller's locals remain alive even though their names are not in scope in the helper. A local in a smaller { ... } block can stop living when that block ends, before the whole function returns. A later call creates fresh parameters and ordinary locals; it does not revive the previous ones. Returning an int copies out a value, so the result survives without keeping the callee's local variable alive.

The call stack is not another name for the heap. Later, allocated-memory lessons will show storage requested explicitly and kept until it is released. None of the helpers here requests that storage.

Before moving on, trace a second call with a starting price of 3 on paper: amount becomes 5, total becomes 10, and the caller's price stays 3. The next exercise asks you to return a calculation of your own.