Handle a missing value
Check a pointer before following it. An easy embedded C problem (A first look at pointers), run and graded in the browser.
easy · A first look at pointers · pointers · null-pointer
A pointer can hold the special value NULL, meaning "this points to nothing". Following a NULL pointer crashes the program, so code checks first.
Return the value p points to, or fallback if p is NULL.
Starter code
int value_or(const int *p, int fallback) {
return *p;
}Example tests
A real value
int x = 7;
printf("%d\n", value_or(&x, 3));Expected output:
7Nothing to point to
printf("%d\n", value_or(NULL, 3));Expected output:
3Learn it first
- A first look at pointers · Addresses, and how a function reaches a variable that belongs to its caller.
More A first look at pointers problems
- Read through a pointer · Follow an address to the value stored there.
- Write through a pointer · Change a variable that belongs to the caller.
- Update a total · Read and write the same variable through a pointer.
- Increment through a pointer · Fix a precedence bug that moves the pointer instead of the value.
- Return two results · Use pointer parameters to hand back more than one value.
- Return a pointer · Hand back the address of an element, or NULL when there is none.