typedef with Structs
Part of the Logic & Flow section of Coddy's C journey — lesson 59 of 63.
One of the most practical applications of typedef is creating aliases for struct types. This eliminates the need to repeatedly write the struct keyword every time you declare a variable of that type, making your code cleaner and more readable.
When you combine typedef with a struct definition, you can create a new type name that refers directly to the struct. Here's the syntax:
typedef struct Point {
int x;
int y;
} Point;Now instead of writing struct Point p1; every time you need a Point variable, you can simply write Point p1;. Both declarations accomplish exactly the same thing, but the typedef version is more concise and easier to read.
This approach is especially valuable in larger programs where you frequently work with custom data types. It makes your code look more like other programming languages and reduces the visual clutter of repeatedly typing struct throughout your program.
Challenge
EasyCreate a C program that demonstrates using typedef with structs to build a simple book inventory system. Your program should:
- Define a
structnamedBookwith the following members:- An integer
id - A character array
titlewith size 50 - A float
price - An integer
quantity
- An integer
- Use
typedefto create a type alias namedBookfor thestruct Book - In the main function:
- Declare two variables of type
Booknamedbook1andbook2 - Read input for the first book in this order: ID, title, price, quantity
- Assign these values to the members of
book1 - Read input for the second book in this order: ID, title, price, quantity
- Assign these values to the members of
book2 - Print the information for both books in this exact format:
Book 1: ID=[id], Title=[title], Price=[price], Quantity=[quantity]Book 2: ID=[id], Title=[title], Price=[price], Quantity=[quantity]
- Calculate and print the total value of each book's inventory (price × quantity) in this exact format:
Book 1 Total Value: [total_value]Book 2 Total Value: [total_value]
- Calculate and print the combined inventory value of both books in this exact format:
Combined Inventory Value: [combined_value] - Determine and print which book has the higher individual value:
- If book1's total value is higher: print
Book 1 has higher value - If book2's total value is higher: print
Book 2 has higher value - If both have equal value: print
Both books have equal value
- If book1's total value is higher: print
- Declare two variables of type
This challenge demonstrates how typedef with structs eliminates the need to repeatedly write struct Book throughout your program. Instead of declaring variables as struct Book book1;, you can simply write Book book1;, making your code cleaner and more readable. You'll practice combining struct definition with typedef, working with struct members, and performing calculations using struct data.
Cheat sheet
Use typedef with structs to create type aliases that eliminate the need to repeatedly write the struct keyword:
typedef struct Point {
int x;
int y;
} Point;Now you can declare variables using the cleaner syntax:
Point p1; // Instead of: struct Point p1;Both declarations accomplish the same thing, but the typedef version is more concise and readable, especially in larger programs with frequent use of custom data types.
Try it yourself
#include <stdio.h>
#include <string.h>
// TODO: Define your struct and typedef here
int main() {
// TODO: Declare your Book variables here
// Read input for first book
int id1, quantity1;
char title1[50];
float price1;
scanf("%d", &id1);
scanf("%s", title1);
scanf("%f", &price1);
scanf("%d", &quantity1);
// TODO: Assign values to book1 members
// Read input for second book
int id2, quantity2;
char title2[50];
float price2;
scanf("%d", &id2);
scanf("%s", title2);
scanf("%f", &price2);
scanf("%d", &quantity2);
// TODO: Assign values to book2 members
// TODO: Print book information, calculate values, and compare
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters7Structures (structs)
What is a Struct?Declaring a StructCreating Struct VariablesAccessing Struct MembersInitializing StructsRecap: Student Data Struct10Enums and Typedef
enum for Named ConstantsDeclaring and Using EnumsEnums in Switch StatementsUsing typedef for Type Aliasestypedef with StructsRecap: Typedef & Enum Practice2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions