C — Modeling a line item with a struct
A C struct gives related fields one type. Store the quantity and unit price in the same struct, then pass that value to a function that calculates the subtotal.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
#include <stdio.h>
int main(void) {
struct Point { int x; };
struct Point point = {2};
printf("%d\n", point.x);
}
2
Represent an invoice line
The struct groups two related integers. Designated initializers document which value is the quantity and which is the unit price. Passing the small struct by value gives subtotal its own copy.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
C17. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 lesson.c -o lesson
./lesson
#include <stdio.h>
struct LineItem { int units; int cents; };
int subtotal(struct LineItem line) {
return line.units * line.cents;
}
int main(void) {
struct LineItem line = {.units = 3, .cents = 125};
printf("%d\n", subtotal(line));
return 0;
}
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.