C / CHAPTER 08
Structs and explicit success results
IntermediateGroup related data and distinguish a missing result from a valid zero.
By the end of this chapter
- Read fields in a struct
- Use a status result with an output parameter
- Preserve caller output on failure
The idea
Start with functions, pointers, and conditions. A struct groups fields that describe one item, such as a quantity and a unit price. A struct value can be copied, while a pointer can borrow the existing record. The dot operator accesses a field through a value; the arrow operator accesses a field through a pointer. Choosing between them follows the type of the expression, not personal formatting preference.
C functions often report success separately from an output value. A boolean return can say whether a lookup found anything, while a pointer receives the answer on success. Define whether failure leaves the output unchanged, and enforce that promise. This avoids using zero or minus one as an ambiguous sentinel when either could be valid data. Validate required pointers according to the documented contract before dereferencing them.
#include <stdbool.h>
#include <stdio.h>
struct Item {int stock;};
bool readStock(const struct Item *item,int *out){if(!item || !out)return false; *out=item->stock; return true;}
int main(void){struct Item a={0}; int stock=99; bool ok=readStock(&a,&stock); printf("%d %d\n",ok,stock);}1 0
The lookup succeeds even though the stored quantity is zero. The status and the returned data communicate different facts.
Try it yourself
Write a function that returns false for an empty array and otherwise writes its first element to an output parameter.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING