Skip to content

Update a Caller Safely

The Course
•
42 min study

A function can return only one value. Converting text into minutes needs two answers: did it work, and if so, what is the number? You could return a special number, such as -1, to mean failure, but then -1 can never be a real result, and a caller who forgets to check will add -1 to the report. C programs usually solve this with an output parameter: the caller passes the address of its own variable, the function writes the result through that pointer, and the return value reports success or failure. Day 6's parser and the final project use exactly this shape.

Predict and run

The second call is given an invalid value. What happens to total?

Predict before running C
#include <stdio.h>

int set_minutes(int value, int *out) {
    if (out == NULL || value < 1 || value > 180) {
        return 0;
    }
    *out = value;
    return 1;
}

int main(void) {
    int total = 10;
    int ok = set_minutes(25, &total);
    printf("%d %d\n", ok, total);
    ok = set_minutes(0, &total);
    printf("%d %d\n", ok, total);
    return 0;
}
Check your prediction
Text
1 25
0 25

The first call passed validation and stored 25 through out. The second returned 0 before reaching the store, so total kept the 25 it already had. Replace &total with NULL in the first call: the guard catches it, the function returns 0, and nothing is dereferenced.

A pointer parameter is still a copy

Nothing about passing changed. The function still receives a copy, but the copied value is an address, and both the original and the copy lead to the same int. That is enough to change it. The classic demonstration is swapping two values, which no function taking plain int parameters can do:

Swap needs addresses C
#include <stdio.h>

void swap(int *a, int *b) {
    int saved = *a;
    *a = *b;
    *b = saved;
}

int main(void) {
    int planned = 30;
    int done = 45;
    swap(&planned, &done);
    printf("%d %d\n", planned, done);
    return 0;
}
Text
45 30

The & at the call site is useful documentation: when you see swap(&planned, &done), you know the call may change both variables. A call that passes plain values cannot.

Validate everything, then write once

The contract for set_minutes has two parts, and both matter to the caller:

  • On success, it returns 1 and *out holds the new value.
  • On failure, it returns 0 and *out is unchanged.

The second promise is what makes the function safe to use. A caller can keep a good default, try an update, and know that a failed update did no damage. To keep it, do all the checking first and write through the pointer only at the end, after nothing else can fail. Compare a version that writes too early:

Writing before validating breaks the promise C
#include <stdio.h>

int set_minutes_early(int value, int *out) {
    *out = value;
    if (value < 1 || value > 180) {
        return 0;
    }
    return 1;
}

int main(void) {
    int total = 25;
    int ok = set_minutes_early(500, &total);
    printf("%d %d\n", ok, total);
    return 0;
}
Text
0 500

It reported failure correctly, yet total is now 500. A caller that trusted the contract would put an invalid duration in the report. This version also has no NULL check, so passing NULL would dereference it on the very first line.

Check the result at the call site

A status result only helps if the caller uses it. The usual pattern puts the call inside the condition, so the value is only used on the success path: if (set_minutes(text_value, &minutes)) { ... }. Returning 1 for success and 0 for failure makes that read naturally, because if treats nonzero as true.

Group fields in a struct

A study session has a label and a duration. Kept in two separate variables (or two arrays), nothing ties them together: a function that should update "the session" needs two pointers, and a caller can pass the label of one session with the minutes of another. A struct declares a new type made of named fields, so one variable holds the whole record:

C
struct Session {
    char label[16];  // at most 15 visible characters plus the terminator
    int minutes;
};

struct Session today = {"C", 25}; fills the fields in order. The dot operator reads or writes one field of a struct variable: today.minutes. A function that should change the caller's record needs its address, exactly as set_minutes did for an int, so it receives a struct Session *. Through a pointer you use the arrow operator: session->minutes means "the minutes field of the struct that session points to". It is shorthand for (*session).minutes; the parentheses would be needed because . binds more tightly than *.

A field updated through a pointer C
#include <stdio.h>

struct Session {
    char label[16];
    int minutes;
};

void lengthen(struct Session *session, int extra) {
    session->minutes = session->minutes + extra;
}

int main(void) {
    struct Session today = {"C", 25};
    printf("%s %d\n", today.label, today.minutes);
    lengthen(&today, 15);
    printf("%s %d\n", today.label, today.minutes);
    return 0;
}
Text
C 25
C 40

Trace it. main owns today, whose minutes is 25. The call passes &today, so session holds the address of today itself, not a copy of the record. Inside, session->minutes reads 25 from today, adds 15 and stores 40 back into today.minutes. The second printf reads the same variable and sees 40. The rule of thumb: a struct variable uses ., a pointer to a struct uses ->.

Fix the wrong operator

This program should reset the session to 0 minutes, but it does not compile. Read the compiler's message, then fix the one line it points to.

Fix: the wrong operator C
#include <stdio.h>

struct Session {
    char label[16];
    int minutes;
};

void reset(struct Session *session) {
    session.minutes = 0;
}

int main(void) {
    struct Session today = {"C", 25};
    reset(&today);
    printf("%s %d\n", today.label, today.minutes);
    return 0;
}
Check your fix

Clang reports member reference type 'struct Session *' is a pointer; did you mean to use '->'?; other compilers word it differently but point at the same line. session is a pointer, so the field is reached with ->:

C
#include <stdio.h>

struct Session {
    char label[16];
    int minutes;
};

void reset(struct Session *session) {
    session->minutes = 0;
}

int main(void) {
    struct Session today = {"C", 25};
    reset(&today);
    printf("%s %d\n", today.label, today.minutes);
    return 0;
}
Text
C 0

The opposite slip, today->minutes on a struct variable, is also a compile error. Both are cheap to fix once you ask "is this name a struct or a pointer to one?" The Day 5 checkpoint puts structs and output parameters together.

Practice

Exercise

Your turn

Write int split_minutes(int total, int *hours, int *minutes). It rejects a negative total or a NULL output, returning 0 and leaving both outputs unchanged. Otherwise it stores the whole hours and leftover minutes and returns 1. Start both outputs at 0, split 125, try to split -5, and print:

Text
125 -> 2:05
-5 rejected, still 2:05
Your workspace C
#include <stdio.h>

int main(void) {
    int hours = 0;
    int minutes = 0;
    // Write your solution here.
    return 0;
}
Hint 1: the idea

All the checks go first, in one condition: either pointer being NULL or the total being negative means failure. Only after that condition has passed do you write through hours and minutes.

Hint 2: a first step

Write the guard first: return 0 when hours is NULL, when minutes is NULL, or when the total is below zero. Then write the two stores using / 60 and % 60.

Show one solution
C
#include <stdio.h>

int split_minutes(int total, int *hours, int *minutes) {
    if (hours == NULL || minutes == NULL || total < 0) {
        return 0;
    }
    *hours = total / 60;
    *minutes = total % 60;
    return 1;
}

int main(void) {
    int hours = 0;
    int minutes = 0;
    if (split_minutes(125, &hours, &minutes)) {
        printf("125 -> %d:%02d\n", hours, minutes);
    }
    if (!split_minutes(-5, &hours, &minutes)) {
        printf("-5 rejected, still %d:%02d\n", hours, minutes);
    }
    return 0;
}
Text
125 -> 2:05
-5 rejected, still 2:05

Because every check happens before the first store, a failed call cannot leave one output updated and the other not. The NULL checks come first in the || chain, and short-circuiting means nothing after a failed check is evaluated. Next you will see what happens when a pointer outlives the object it points to.

Was this article helpful?

Your response is saved on this device.