Initializing Structs
Part of the Logic & Flow section of Coddy's C journey — lesson 42 of 63.
While you can create struct variables and then assign values to their members individually, C provides a more convenient way to set initial values. You can initialize a struct variable at the time of declaration using an initializer list enclosed in curly braces.
The syntax for struct initialization is:
struct StructureName variableName = {value1, value2, ...};Using our Point struct example, you can declare and initialize it in one clean line:
struct Point p1 = {10, 20};This creates a Point variable named p1 with x set to 10 and y set to 20. The values in the initializer list are assigned to the struct members in the order they were declared in the struct definition.
This initialization approach is not only more concise than separate assignments, but it also ensures your struct starts with meaningful values rather than random garbage data. It's particularly useful when you know the initial values at compile time and want to create ready-to-use struct variables efficiently.
Challenge
EasyCreate a C program that demonstrates struct initialization using initializer lists. Your program should:
- Define a
structnamedEmployeewith the following members:- An integer
idto store the employee ID - A character array
departmentwith size 15 to store the department name - An integer
yearsOfServiceto store years of service - A float
salaryto store the employee's salary
- An integer
- Create three
Employeevariables using initializer lists with the following data:emp1: ID 101, department "Engineering", 5 years of service, salary 75000.50emp2: ID 102, department "Marketing", 3 years of service, salary 65000.25emp3: ID 103, department "Sales", 8 years of service, salary 80000.75
- Print the information for each employee in this exact format:
Employee 1:ID: [id]Department: [department]Years of Service: [yearsOfService]Salary: [salary]Employee 2:ID: [id]Department: [department]Years of Service: [yearsOfService]Salary: [salary]Employee 3:ID: [id]Department: [department]Years of Service: [yearsOfService]Salary: [salary]
- Calculate and print the total salary of all three employees in the format:
Total Salary: [total] - Calculate and print the average years of service in the format:
Average Years of Service: [average]
This challenge tests your understanding of struct initialization using initializer lists, where you declare and initialize struct variables in a single line. The values in the initializer list must be provided in the same order as the members were declared in the struct definition.
Your expected output should be:
Employee 1:
ID: 101
Department: Engineering
Years of Service: 5
Salary: 75000.50
Employee 2:
ID: 102
Department: Marketing
Years of Service: 3
Salary: 65000.25
Employee 3:
ID: 103
Department: Sales
Years of Service: 8
Salary: 80000.75
Total Salary: 220001.50
Average Years of Service: 5.33Cheat sheet
You can initialize a struct variable at declaration time using an initializer list enclosed in curly braces:
struct StructureName variableName = {value1, value2, ...};Example with a Point struct:
struct Point p1 = {10, 20};The values in the initializer list are assigned to struct members in the order they were declared in the struct definition. This approach is more concise than separate assignments and ensures your struct starts with meaningful values rather than random garbage data.
Try it yourself
#include <stdio.h>
// TODO: Define the Employee struct here
int main() {
// TODO: Create three Employee variables using initializer lists
// TODO: Print information for each employee
// TODO: Calculate and print total salary and average years of service
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 Struct2Pointers 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