Structures and Functions
A structure can be a parameter of a function. Instead of three parameters for the name, the price and the count, the function gets one product:
#include <stdio.h>
typedef struct {
char name[20];
double price;
int count;
} Product;
double line_total(Product item) {
return item.price * item.count;
}
int main(void) {
Product milk = {"Milk", 24.9, 3};
printf("%s: %.2f\n", milk.name, line_total(milk));
return 0;
}This prints:
Milk: 74.70The definition of Product must be above the function, because the function uses the type. That's why structures are usually defined at the very top of the program, right below the #includes.
When you call line_total(milk), the parameter item gets a copy of the whole structure: all its members, including the text in name. It's the same as with an int parameter, and different from an array, which a function gets without copying. So when the function changes its parameter, it changes only the copy:
#include <stdio.h>
typedef struct {
char name[20];
double price;
int count;
} Product;
void sell_one(Product item) {
item.count--;
printf("In the function: %d\n", item.count);
}
int main(void) {
Product milk = {"Milk", 24.9, 3};
sell_one(milk);
printf("In main: %d\n", milk.count);
return 0;
}This prints:
In the function: 2
In main: 3The function sold one carton of milk, but only from its copy: milk in main still has 3. In the next exercise, you will see how a function can change the original. For functions that only read the structure, like line_total, the copy doesn't matter.
Assigning one structure to another with = copies it too. After Product copy = milk;, the variable copy has its own name, price and count, and changing copy.count doesn't change milk. Even the array name inside it is copied, although an array on its own can't be assigned. You can't compare two structures with ==, though: milk == copy ends with the error invalid operands to binary expression ('Product' and 'Product'). Compare the members you need instead, such as milk.price == copy.price, and the names with strcmp.
Instructions
In place of the comment, write a function double area(Room room) that returns the area of the room: its width times its length.
In the loop, print the area of each room next to its name, with 2 decimal places, and get it from your function area. The program prints Kitchen: 13.50 m2, Bedroom: 14.00 m2 and Hallway: 9.00 m2.
Start programming for free
6/9