typedef
Writing struct product every time you create a variable is a lot of typing. And when you forget the word struct, as in product bread = {"Bread", 32.5, 2};, the program doesn't compile:
main.c:10:5: error: must use 'struct' tag to refer to type 'product'
10 | product bread = {"Bread", 32.5, 2};
| ^
| structIn C, the name of a structure works only together with the word struct. With the keyword typedef (short for type definition), you can give the type a name of its own. Write typedef before struct, and the new name after the closing curly brace:
typedef struct {
char name[20];
double price;
int count;
} Product;Now the type is called simply Product, and you create its variables the way you create int variables:
Product bread = {"Bread", 32.5, 2};
Product milk = {"Milk", 24.9, 3};The name after struct isn't needed any more: the structure now has the name Product from typedef. Many programmers start the names of types with a capital letter, so that they can tell them from variables, and so does this course: Product is a type, bread and milk are variables. Don't forget the semicolon after the new name.
From now on, this course writes structures with typedef. In other programs you will see both forms, and sometimes they are combined: after typedef struct product { ... } Product;, both struct product and Product work.
Watch out for one thing: a structure defined with typedef this way has no name after struct, so struct Product bread doesn't work. The error is not very clear:
main.c:10:20: error: variable has incomplete type 'struct Product'
10 | struct Product bread = {"Bread", 32.5, 2};
| ^An incomplete type is a type that the compiler knows only by name, without its members. Because of the word struct, it looks for a structure named struct Product, and there is none. Leave out the struct and write just Product bread.
Instructions
Rewrite the structure with typedef so that the type is called Song, and create both variables as Song. The program prints the same two lines as before.
Below the variable second, create a third song third of type Song with the title Last Bus Home and the length 251 seconds. Print it the same way, below the other two. The last line is Last Bus Home: 4 min 11 s.
Start programming for free
3/9