C NULL pointer guard
Use a null pointer to represent an absent phone field and check it before printing the string.
A simple example
NULL pointer guard
- Start with No string supplied
- Do this Try to read its length
- Result No length available
Syntax
phone == NULL
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonPrint a label when the phone number is missing
A school prints contact cards from an enrollment form. Some families leave the optional phone field blank, so the printer needs a readable fallback before it measures or displays that field.
#include <stdio.h>
int main(void) {
const char *phone = NULL;
puts(phone == NULL ? "Ask for a phone number" : phone);
return 0;
}
Ask for a phone number
The missing contact follows the fallback branch, so the card still has a printable phone field.
Print an existing extension
A department saved its internal extension in the staff directory. Confirm that a contact value is available before printing it on a dispatch slip.
Flag an unfilled contact field
A delivery booking reaches reception without a contact value. Confirm that a contact value is available before printing it on a dispatch slip.
What to watch for
The %s conversion requires a valid string pointer. Passing a null pointer has undefined behavior.