MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Initializing Structures

Initializing structures in programming involves setting the values of structure members at the time of declaration. This can be done in several ways, depending on the programming language being used. Here's an explanation with examples in C.

Basic Structure Initialization

You can initialize a structure at the time of declaration by providing a list of values in curly braces. The values are assigned to the structure members in the order they are declared.

Example

Consider the Person structure from the previous example:

struct Person {
char name[50]; int age; float height; };

You can initialize an instance of this structure as follows:

struct Person person1 = {"John Doe", 30, 5.9};

here, "John Doe" is assigned to the name member, 30 is assigned to the age member, 5.9 is assigned to the height member.


Newer / Advanced Concepts 

Designated Initializers (C99 and later)

C99 introduced designated initializers, which allow you to specify the values for specific members of the structure. This makes the code more readable and less error-prone, especially when dealing with large structures.

Example

You can use designated initializers like this:

struct Person person2 = {.name = "Jane Smith", .age = 25, .height = 5.7};

In this case, the values are explicitly assigned to the corresponding members, regardless of their order in the structure definition.

Partial Initialization

If you do not provide initializers for all members, the uninitialized members are set to zero (or equivalent for the member type).

Example

struct Person person3 = {"Alice"};

here, name is initialized to "Alice", age is initialized to 0 (default integer value), height is initialized to 0.0 (default float value).


Report an issue

Reporting: Initializing Structures (topic)

Related Posts