• C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

How to Initialize Structures in C?

  • How to Initialize 3D Vector in C++ STL?
  • How to Initialize Array of Pointers in C?
  • How to avoid Structure Padding in C?
  • Structure Pointer in C
  • How to Initialize an Array in C++?
  • When do we use Initializer List in C++?
  • How to Initialize a 2D Array in C?
  • How to Initialize a 3D Array in C?
  • How to Initialize a Set with an Array in C++?
  • std::initializer_list in C++ 11
  • Structures in Objective-C
  • Pointers to Structures in Objective C
  • How to Initialize an Array in Java?
  • How to Initialize Multimap with Default Values in C++?
  • How to Access Array of Structure in C?
  • How to Declare and Initialize an Array of Pointers to a Structure in C?
  • How to Declare a Struct Inside a Struct in C?
  • C++ - Pointer to Structure
  • Pointer to a Struct in Golang

In C, a structure (struct) is a user-defined data type that allows us to combine data items of different data types into a single unit. In this article, we will learn how to initialize structures in C.

Initialize Structures in C

We can initialize the structure by providing the values of the members in the list during the declaration. The values in the list will be then assigned to the member of the structure sequentially. It means the first value in the list will be assigned to the first member and so on.

To initialize the structure member non-sequentially, we can use the designated initialization technique where we initialize the members using their names.

Syntax to Initialize Structures in C

Designated Initialization:

C Program to Initialize Structures

Time Complexity: O(N), where N is the number of members in the struct. Auxiliary Space: O(1)

Please Login to comment...

Similar reads.

  • C-Structure & Union

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • How to Initialize a Struct in C

Use Designated Initializers to Initialize a Struct in C

Use compound literals to initialize a struct in c, use explicit assignments to initialize a struct in c, use constructors (in c99 and later) to initialize a struct in c.

How to Initialize a Struct in C

Structs in C provide a powerful mechanism for grouping variables of diverse data types under a unified name. Properly initializing a struct is crucial for ensuring the correct functioning of your programs.

In this article, we’ll explore various methods to initialize a struct in C, each offering its advantages.

In C programming, structs serve as a pivotal tool for grouping variables of diverse data types under a unified name. When it comes to initializing a struct, one particularly versatile technique is the use of designated initializers.

This method allows for explicit specification of which members of the struct to initialize, offering clarity and flexibility in code organization.

The syntax for designated initializers involves specifying the member name followed by an equal sign and the value to assign. The general form looks like this:

This syntax allows initializing specific members of the struct while leaving others uninitialized, fostering flexibility in struct initialization.

Let’s dive into an example featuring a Person struct, representing an individual’s first name, last name, age, and a boolean indicating their vitality. Designated initializers will be employed to create an instance of this struct.

In this code snippet, we include necessary header files ( stdbool.h , stdio.h , stdlib.h , string.h ) and define a Person struct using typedef . The struct encapsulates members for the first name ( firstname ), last name ( lastname ), age, and a boolean indicating whether the person is alive ( alive ).

In the main function, we create an instance of the Person struct named me . Using designated initializers, we initialize each member of the struct with specific values.

The first name is set to John , the last name to McCarthy , the age to 24 , and the alive status to true .

The subsequent printf statement displays the information stored in the me struct. It prints the first name, last name, and age using the %s and %d format specifiers, respectively.

The last part of the output depends on the boolean value of the alive member. If alive is true , Yes is printed; otherwise, No is printed.

Finally, the program exits with EXIT_SUCCESS , indicating successful execution.

Another versatile technique to initialize a struct is using compound literals. This method allows for the creation of temporary instances of a struct with specific initial values.

The syntax for compound literals involves enclosing a list of values within parentheses and casting them to the desired struct type. The general form looks like this:

This syntax allows for the creation of an unnamed temporary instance of the struct with the specified initial values.

Let’s delve into a practical example using the Person struct:

In this example, we have a Person struct representing an individual’s first name, last name, age, and alive status. The main function initializes an instance of this struct named me using a compound literal.

The compound literal (Person){.firstname = "John\0", .lastname = "McCarthy\0", .age = 24, .alive = 1} creates a temporary instance of the Person struct with each member explicitly initialized.

This method combines clarity and conciseness, eliminating the need for a separate declaration and assignment step.

The subsequent printf statement displays the information stored in the me struct, presenting the first name, last name, age, and alive status. The output, in this case, would be:

Using compound literals in this manner enhances the readability of the code, making it clear and expressive. This approach is particularly advantageous when immediate struct initialization is preferred, providing a streamlined and elegant solution for struct initialization in C.

When initializing struct members in C, an alternative method involves declaring a variable and assigning each member with its corresponding value individually. This approach is characterized by explicit assignments, making it clear and straightforward.

It’s worth noting that when dealing with char arrays, assigning them directly with strings isn’t allowed in C. Instead, explicit copying using functions like memcpy or memmove is necessary (refer to the manual for more details).

Additionally, care should be taken to ensure that the length of the array is not less than the string being stored.

Here’s an illustrative example using a Person struct:

As we can see in this example, each member of the me2 instance is assigned a value individually. Here, the use of memcpy ensures the proper copying of string values into char arrays, respecting the necessary length constraints.

The subsequent printf statement remains unchanged, displaying the information stored in the me2 struct. The output, as before, will be:

While this approach is valid, it often involves more lines of code and can be less concise compared to using compound literals, as demonstrated in the previous section.

Compound literals provide a more streamlined and expressive way to initialize structs in C, especially when dealing with immediate initialization or temporary instances.

The concept of constructors, while not native, like in some other languages, can be emulated to achieve struct initialization.

C99 and later versions allow for a more expressive and organized approach by enabling the use of designated initializers within functions. This technique can be likened to a constructor, allowing for structured and customizable initialization of structs.

The syntax for creating a constructor-like function involves defining a function that returns an instance of the struct with designated initializers.

Here’s an example using a Person struct:

In this example, we define a Person struct with members for the first name, last name, age, and alive status. Here, the createPerson function serves as a constructor-like function, initializing and configuring a Person struct with specific values.

The function uses strncpy to copy the first and last names into the struct’s firstname and lastname members, respectively. It also ensures null-termination of the strings to prevent potential buffer overflows.

The age and alive members are then set according to the provided arguments.

In the main function, the createPerson function is used to initialize a Person struct named me . The subsequent printf statement displays the information stored in the me struct, showcasing the first name, last name, age, and alive status.

This constructor-like approach offers a structured and modular way to initialize structs in C, providing a clear and organized solution for customizable struct initialization.

Initializing structs in C involves a range of techniques, each catering to different preferences and scenarios.

Designated initializers offer clarity and flexibility, whereas compound literals provide immediate initialization. Explicit assignments ensure straightforward initialization and constructors (in C99 and later) allow for a structured approach.

Choose the method that aligns with your coding style and the specific requirements of your program. Whether you prioritize clarity, conciseness, or modularity, understanding these initialization techniques will empower you to write more efficient and maintainable C code.

Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article - C Struct

  • Bit Field in C
  • Difference Between Struct and Typedef Struct in C
  • How to Use struct Alignment and Padding in C
  • How to Initialize Array of Structs in C
  • How to Return a Struct From Function in C
  • How to Allocate Struct Memory With malloc in C

Codeforwin

How to declare, initialize and access structures in C language

  • Declare structure
  • Initialize structure
  • Example program

Write a C program to declare, initialize and access structures. In this post I will explain how to declare, initialize and access structures in C language. Different ways to initialize a structure variable and how to access structure members.

Required knowledge

Basic C programming , Structures

Declare, initialize and access structures in C programming language

What is structure in C language?

Structure is a user defined data type . It is a collection of different types combined together to create a new type.

How to declare a structure?

We use struct keyword to declare a structure.

Let us declare a student structure containing three fields i.e. name , roll and marks .

How to initialize a structure variable?

C language supports multiple ways to initialize a structure variable. You can use any of the initialization method to initialize your structure.

  • Initialize using dot operator

Value initialized structure variable

Variant of value initialized structure variable, initialize structure using dot operator.

In C, we initialize or access a structure variable either through dot . or arrow -> operator . This is the most easiest way to initialize or access a structure.

The above method is easy and straightforward to initialize a structure variable. However, C language also supports value initialization for structure variable. Means, you can initialize a structure to some default value during its variable declaration.

Note: The values for the value initialized structure should match the order in which structure members are declared.

Invalid initialization:

The above code will throw compilation error . Since the order of member type in structure is character array , integer finally float. But, we aren’t initializing the structure variable in the same order.

The above approach may suit all needs. In addition, C language supports flexibility to initialize structure members in any order. I know this sounds bit confusing. As, just now I said C will throw error if you try to initialize members in different order of declaration.

This approach is an extension of above. Here, you can specify member name along with the value.

Structure default initialization

Default initialization of a variable considered as good programming practice. However, C doesn’t support any programming construct for default structure initialization. You manually need to initialize all fields to 0 or NULL .

Initializing all fields to NULL is bit cumbersome process. Let’s do a small hack to initialize structure members to default value, on every structure variable declaration.

Program to declare, initialize and access structure

Happy coding 😉

Next: Designated Inits , Previous: Variable Declarations , Up: Variables   [ Contents ][ Index ]

20.2 Initializers

A variable’s declaration, unless it is extern , should also specify its initial value. For numeric and pointer-type variables, the initializer is an expression for the value. If necessary, it is converted to the variable’s type, just as in an assignment.

You can also initialize a local structure-type (see Structures ) or local union-type (see Unions ) variable this way, from an expression whose value has the same type. But you can’t initialize an array this way (see Arrays ), since arrays are not first-class objects in C (see Limitations of C Arrays ) and there is no array assignment.

You can initialize arrays and structures componentwise, with a list of the elements or components. You can initialize a union with any one of its alternatives.

You can omit the size of the array when you declare it, and let the initializer specify the size:

  • A component-wise initializer for a structure consists of field values surrounded by ‘ { … } ’. Write the field values in the same order as the fields are declared in the structure. If the values in the initializer don’t cover all the fields in the structure, the remaining fields are initialized to zero.
  • The initializer for a union-type variable has the form { value } , where value initializes the first alternative in the union definition.

For an array of arrays, a structure containing arrays, an array of structures, etc., you can nest these constructs. For example,

You can omit a pair of inner braces if they contain the right number of elements for the sub-value they initialize, so that no elements or fields need to be filled in with zeros. But don’t do that very much, as it gets confusing.

An array of char can be initialized using a string constant. Recall that the string constant includes an implicit null character at the end (see String Constants ). Using a string constant as initializer means to use its contents as the initial values of the array elements. Here are examples:

and this kind of initializer can be nested inside braces to initialize structures or arrays that contain a char -array.

In like manner, you can use a wide string constant to initialize an array of wchar_t .

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, introduction.

  • Getting Started with C
  • Your First C Program
  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples

Programming Strings

  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

Structure and Union

C structs and Pointers

C Structure and Function

Programming Files

  • C File Handling
  • C Files Examples

Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

C Struct Examples

  • Add Two Complex Numbers by Passing Structure to a Function
  • Add Two Distances (in inch-feet system) using Structures

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

  • Define Structures

Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used.

Syntax of struct

For example,

Here, a derived type struct Person is defined. Now, you can create variables of this type.

Create struct Variables

When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables.

Here's how we create structure variables:

Another way of creating a struct variable is:

In both cases,

  • person1 and person2 are struct Person variables
  • p[] is a struct Person array of size 20.

Access Members of a Structure

There are two types of operators used for accessing members of a structure.

  • . - Member operator
  • -> - Structure pointer operator (will be discussed in the next tutorial)

Suppose, you want to access the salary of person2 . Here's how you can do it.

Example 1: C structs

In this program, we have created a struct named Person . We have also created a variable of Person named person1 .

In main() , we have assigned values to the variables defined in Person for the person1 object.

Notice that we have used strcpy() function to assign the value to person1.name .

This is because name is a char array ( C-string ) and we cannot use the assignment operator = with it after we have declared the string.

Finally, we printed the data of person1 .

  • Keyword typedef

We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables.

For example, let us look at the following code:

We can use typedef to write an equivalent code with a simplified syntax:

Example 2: C typedef

Here, we have used typedef with the Person structure to create an alias person .

Now, we can simply declare a Person variable using the person alias:

  • Nested Structures

You can create structures within a structure in C programming. For example,

Suppose, you want to set imag of num2 variable to 11 . Here's how you can do it:

Example 3: C Nested Structures

Why structs in c.

Suppose you want to store information about a person: his/her name, citizenship number, and salary. You can create different variables name , citNo and salary to store this information.

What if you need to store information of more than one person? Now, you need to create different variables for each information per person: name1 , citNo1 , salary1 , name2 , citNo2 , salary2 , etc.

A better approach would be to have a collection of all related information under a single name Person structure and use it for every person.

More on struct

  • Structures and pointers
  • Passing structures to a function

Table of Contents

  • C struct (Introduction)
  • Create struct variables
  • Access members of a structure
  • Example 1: C++ structs

Sorry about that.

Related Tutorials

Search anything:

Initialize struct in C [3 ways]

C programming.

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

In this article, we have explored how to initialize struct in C Programming Language using different techniques such as designated initializer, dot operator and more.

Only a single data type can be stored in an array (if you declare a char type, you cannot store anything other than char type), but by using the structure in C language, we can combine variables with different data types into one.

Table of Contents :

  • Introduction

USE A Struct

  • Structure initialization
  • Initialization at Declaration
  • Initialization using Designated Initializer
  • Initialized at compile time using the dot(.) operator

When should the structure be initialized?

Introduction.

A structure is a function that allows you to collectively manage multiple values. It can also be said that it is a function that creates a new data type by gathering multiple data types.

struct in simpler terms can be said to be the keyword for "I'm going to define a structure now."

Arrays are also a function that can handle multiple values collectively, but whereas arrays are collections of the same data type, structures can collectively manage different data types.

A variable defined in a structure is called a member variable .

Basic steps to write a struct in C :

  • Write the structure name following struct. You can decide the structure name as you like.
  • Next, create a block with curly braces {}.
  • Inside this block, define one or more variables that you want to use in your structure.
  • In the sample code, name is defined as a char type array, marks is defined as an int type, and a structure is created to store Subject information.
  • Don't forget to end the block with a semicolon (;).
  • A function definition didn't need a semicolon, so it's easy to forget it in a struct definition.

We use the dot operator to access member variables from structure variables. Write "." (dot, period) after the structure variable, and then write the name of the member variable you want to use.

Structure initialization in C

C language offers us many ways to initialize a structure in our program. We can use the following initialization method to initialize struct:

Structure variables can be initialized at the same time they are declared, just like normal variables and arrays.

General form: structure type structure variable = { value1, value2, ... };

Following C code demonstrates Initialization of struct using Designated Initializer:

Note : Order of assigning the variables do not matter.

Structure variable can be initialized at compile time using the dot(.) operator. Initialization that directly assigns values to members of structure variables.

First of all, the structure may be initialized when the structure variable is created.

By initializing the structure variables by clearing them to 0, bugs related to the variables can be reduced. If the structure has a pointer it may contain a random value unless it is initialized. In the code after that, it is not possible to judge whether the value of the pointer is a proper memory address or a random value that has not been initialized.

Therefore, if you clear the structure variable to 0 and set the pointer to NULL when creating the structure variable for the first time, you can reduce the bug errors.

We have seen the initialization of structures in C language in this article at OpenGenus. We found out that there are a multiple ways to initialize the structure like below:

Which one to use solely depends on the judgment of the programmer.

OpenGenus IQ: Learn Algorithms, DL, System Design icon

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Brace initialization

  • 9 contributors

It isn't always necessary to define a constructor for a class , especially ones that are relatively simple. Users can initialize objects of a class or struct by using uniform initialization, as shown in the following example:

When a class or struct has no constructor, you provide the list elements in the order that the members are declared in the class . If the class has a constructor, provide the elements in the order of the parameters. If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization:

If a class has non-default constructors, the order in which class members appear in the brace initializer is the order in which the corresponding parameters appear in the constructor, not the order in which the members are declared (as with class_a in the previous example). Otherwise, if the type has no declared constructor, member initializers must appear in the brace initializer in the same order as they're declared. In this case, you can initialize as many of the public members as you wish, but you can't skip any member. The following example shows the order that's used in brace initialization when there's no declared constructor:

If the default constructor is explicitly declared but marked as deleted, empty brace initialization can't be used:

You can use brace initialization anywhere you would typically do initialization—for example, as a function parameter or a return value, or with the new keyword:

In /std:c++17 mode and later, the rules for empty brace initialization are slightly more restrictive. See Derived constructors and extended aggregate initialization .

initializer_list constructors

The initializer_list Class represents a list of objects of a specified type that can be used in a constructor, and in other contexts. You can construct an initializer_list by using brace initialization:

To use this class, you must include the <initializer_list> header.

An initializer_list can be copied. In this case, the members of the new list are references to the members of the original list:

The standard library container classes, and also string , wstring , and regex , have initializer_list constructors. The following examples show how to do brace initialization with these constructors:

Classes and Structs Constructors

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

C# and Python programming, machine learning, quantitative finance, numerical methods

struct inline initialization c

Inline Initialization

I must admit that I was rather surprised when I learnt that inline initialization translates into the default constructor-based initialization in the IL. So, for example, these two pieces of code are equivalent:

is the same as

The above can be verified by examining the IL of the first example through the ILDASM. Below I am showing the snapshot of what the IL code in .ctor generated by the IL looks like:

InLineIL

As pointed out in ([1], chapter 8), this means that non-constant fields initialized inline lead to the IL code explosion.

In one of my previous posts on C# language features I wrote that parameter-less constructors are not allowed in value types before C# 6.0. This is the reason why inline initialization is illegal in structs. For example, the following won’t compile:

If you examine the IL for the struct, you will see that it has no code for the default .ctor. The implicit parameter-less constructor is intrinsic to the struct (i.e. it is provided by the C# language implementation) and cannot be modified. Thus, for C# struct, there is no way to translate the inline initializers into the initialization inside the parameter-less constructor.

The story is very different for static fields. In value types, static fields can be initialized inline. As you may have already guessed, such initialization does translate into the parameter-less static constructor initialization. For example, these two pieces of code are equivalent in the IL:

References: [1] J.Richter. CLR via C#, 4th edition. 2014.

Share this:

5 thoughts on “ inline initialization ”.

Sorry, just realised I wrote something a bit non-sensical, I was trying to refer to this: http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx

Or to go in another direction, have a look at the fun that happens with static type initializers vs static constructors http://csharpindepth.com/Articles/General/Beforefieldinit.aspx

Aha! This is indeed a very good point, and goes beyond my naive “discovery” about inline initializers becoming a part of the class’s default constructor.

Thanks for pointing me to Eric’s article which is about the order of field initialization and constructor calls, as well as the reason for why C# behaves like it does, especially with the readonly fields.

Now that I know that inline initialization becomes a part of the default constructor’s code, it is important to highlight, as you suggest, that the order in which that field initialization and the native constructor’s instructions happen is something to be aware of. That is, the fields are initialized before anything else.

I guess this may be a good description for how the code in Eric’s article is executed:

1. The readonly derivedFoo initialization becomes part of Derived constructor, and executes first via a call to Foo’s constructor. The 1st line of output is: “Foo constructor: Derived initializer”. 2. Since Derived class is a subclass of Base, the Base’s constructor is called next. Here we have that Base class baseFoo initialization is a part of Base’s constructor! Thus, Foo’s constructor is called again. The 2nd line of output is: “Foo constructor: Base initializer”. 3. Base class constructor continue’s with the rest of its instructions. The 3rd line of output therefore is: “Base constructor”. 4. Finally, the rest of the Derived class constructor’s code is executed. We have the last line of output: “Derived constructor”.

Thank you, GrahamTheCoder for this suggestion!

If the Inline sub-class has inline field initializers, then these become part of the sub-class constructor. Also, as the case with the Inline class, the constructor of the parent class is called. For Inline sub-class the parent is Inline, so, its default constructor is called again.

If you haven’t already, have a look at what happens when you have a subclass of Inline with a field initializer too, it is perfectly sensible but goes against some people’s intuition.

Comments are closed.

Ideas, Papers and Thoughts on the field of Visualization

' src=

  • Already have a WordPress.com account? Log in now.
  • Subscribe Subscribed
  • Copy shortlink
  • Report this content
  • View post in Reader
  • Manage subscriptions
  • Collapse this bar

Learn C++

13.8 — Struct aggregate initialization

In the previous lesson ( 13.7 -- Introduction to structs, members, and member selection ), we talked about how to define structs, instantiate struct objects, and access their members. In this lesson, we’ll discuss how structs are initialized.

Data members are not initialized by default

Much like normal variables, data members are not initialized by default. Consider the following struct:

Because we have not provided any initializers, when joe is instantiated, joe.id , joe.age , and joe.wage will all be uninitialized. We will then get undefined behavior when we try to print the value of joe.id .

However, before we show you how to initialize a struct, let’s take a short detour.

What is an aggregate?

In general programming, an aggregate data type (also called an aggregate ) is any type that can contain multiple data members. Some types of aggregates allow members to have different types (e.g. structs), while others require that all members must be of a single type (e.g. arrays).

In C++, the definition of an aggregate is narrower and quite a bit more complicated.

Author’s note

In this tutorial series, when we use the term “aggregate” (or “non-aggregate”) we will mean the C++ definition of aggregate.

For advanced readers

To simplify a bit, an aggregate in C++ is either a C-style array ( 17.7 -- Introduction to C-style arrays ), or a class type (struct, class, or union) that has:

  • No user-declared constructors ( 14.9 -- Introduction to constructors )
  • No private or protected non-static data members ( 14.5 -- Public and private members and access specifiers )
  • No virtual functions ( 25.2 -- Virtual functions and polymorphism )

The popular type std::array ( 17.1 -- Introduction to std::array ) is also an aggregate.

You can find the precise definition of a C++ aggregate here .

The key thing to understand at this point is that structs with only data members are aggregates.

Aggregate initialization of a struct

Because a normal variable can only hold a single value, we only need to provide a single initializer:

However, a struct can have multiple members:

When we define an object with a struct type, we need some way to initialize multiple members at initialization time:

Aggregates use a form of initialization called aggregate initialization , which allows us to directly initialize the members of aggregates. To do this, we provide an initializer list as an initializer, which is just a braced list of comma-separated values.

There are 2 primary forms of aggregate initialization:

Each of these initialization forms does a memberwise initialization , which means each member in the struct is initialized in the order of declaration. Thus, Employee joe { 2, 28, 45000.0 }; first initializes joe.id with value 2 , then joe.age with value 28 , and joe.wage with value 45000.0 last.

Best practice

Prefer the (non-copy) braced list form when initializing aggregates.

In C++20, we can also initialize (some) aggregates using a parenthesized list of values:

We recommend avoiding this last form as much as possible, as it doesn’t currently work with aggregates that utilize brace elision (notably std::array ).

Missing initializers in an initializer list

If an aggregate is initialized but the number of initialization values is fewer than the number of members, then all remaining members are initialized with an empty initializer list. In most cases, this will perform value-initialization on those members.

In the above example, joe.id will be initialized with value 2 joe.age will be initialized with value 28 , and because joe.wage wasn’t given an explicit initializer, it will be value-initialized to 0.0 .

This means we can generally use an empty initialization list to value-initialize all members of the struct:

Const structs

Variables of a struct type can be const (or constexpr), and just like all const variables, they must be initialized.

Designated initializers C++20

When initializing a struct from a list of values, the initializers are applied to the members in order of declaration.

Now consider what would happen if you were to update this struct definition to add a new member that is not the last member:

Now all your initialization values have shifted, and worse, the compiler may not detect this as an error (after all, the syntax is still valid).

To help avoid this, C++20 adds a new way to initialize struct members called designated initializers . Designated initializers allow you to explicitly define which initialization values map to which members. The members can be initialized using list or copy initialization, and must be initialized in the same order in which they are declared in the struct, otherwise a warning or error will result. Members not designated an initializer will be value initialized.

For Clang users

When doing designated initializers of single values using braces, Clang improperly issues warning “braces around scalar initializer”. Hopefully this will be fixed soon.

Designated initializers are nice because they provide some level of self-documentation and help ensure you don’t inadvertently mix up the order of your initialization values. However, designated initializers also clutter up the initializer list significantly, so we won’t recommend their use as a best practice at this time.

Also, because there’s no enforcement that designated initializers are being used consistently everywhere an aggregate is initialized, it’s a good idea to avoid adding new members to the middle of an existing aggregate definition, to avoid the risk of initializer shifting.

When adding a new member to an aggregate, it’s safest to add it to the bottom of the definition list so the initializers for other members don’t shift.

Assignment with an initializer list

As shown in the prior lesson, we can assign values to members of structs individually:

This is fine for single members, but not great when we want to update many members. Similar to initializing a struct with an initializer list, you can also assign values to structs using an initializer list (which does memberwise assignment):

Note that because we didn’t want to change joe.id , we needed to provide the current value for joe.id in our list as a placeholder, so that memberwise assignment could assign joe.id to joe.id . This is a bit ugly.

Assignment with designated initializers C++20

Designated initializers can also be used in a list assignment:

Any members that aren’t designated in such an assignment will be assigned the value that would be used for value initialization. If we hadn’t have specified a designated initializer for joe.id , joe.id would have been assigned the value 0.

Initializing a struct with another struct of the same type

A struct may also be initialized using another struct of the same type:

The above prints:

Note that this uses the standard forms of initialization that we’re familiar with (copy, direct, or list initialization) rather than aggregate initialization.

This is most commonly seen when initializing a struct with the return value of a function that returns a struct of the same type. We cover this in more detail in lesson 13.10 -- Passing and returning structs .

guest

cppreference.com

Constructors and member initializer lists.

Constructors are non-static member functions declared with a special declarator syntax, they are used to initialize objects of their class types.

[ edit ] Syntax

Constructors are declared using member function declarators of the following form:

The only specifiers allowed in the declaration specifiers of a constructor declaration are friend , inline , constexpr (since C++11) , consteval (since C++20) , and explicit (in particular, no return type is allowed). Note that cv- and ref-qualifiers are not allowed either: const and volatile semantics of an object under construction only kick in after the most-derived constructor completes.

The id-expression of class-name must have one of the following forms:

  • In a friend declaration , the id-expression is a qualified identifier that names a constructor .
  • Otherwise, in a member declaration that belongs to the member specification of a class or class template:
  • For classes, the id-expression is the injected-class-name of the immediately-enclosing class.
  • For class templates, the id-expression is a class name that names the current instantiation (until C++20) the injected-class-name (since C++20) of the immediately-enclosing class template.
  • Otherwise, the id-expression is a qualified identifier whose terminal unqualified identifier is the injected-class-name of its lookup context.

[ edit ] Member initializer list

The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list , whose syntax is the colon character : , followed by the comma-separated list of one or more member-initializers , each of which has the following syntax:

[ edit ] Explanation

Constructors have no names and cannot be called directly. They are invoked when initialization takes place, and they are selected according to the rules of initialization. The constructors without explicit specifier are converting constructors . The constructors with a constexpr specifier make their type a LiteralType . Constructors that may be called without any argument are default constructors . Constructors that take another object of the same type as the argument are copy constructors and move constructors .

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. The member initializer list is the place where non-default initialization of these subobjects can be specified. For bases that cannot be default-initialized and for non-static data members that cannot be initialized by default-initialization or by their default member initializer , if any (since C++11) , such as members of reference and const-qualified types, member initializers must be specified. (Note that default member initializers for non-static data members of class template instantiations may be invalid if the member type or initializer is dependent.) (since C++11) No initialization is performed for anonymous unions or variant members that do not have a member initializer or default member initializer (since C++11) .

The initializers where class-or-identifier names a virtual base class are ignored during construction of any class that is not the most derived class of the object that's being constructed.

Names that appear in expression-list or brace-init-list are evaluated in scope of the constructor:

Exceptions that are thrown from member initializers may be handled by function-try-block .

Member functions (including virtual member functions) can be called from member initializers, but the behavior is undefined if not all direct bases are initialized at that point.

For virtual calls (if the direct bases are initialized at that point), the same rules apply as the rules for the virtual calls from constructors and destructors: virtual member functions behave as if the dynamic type of * this is the static type of the class that's being constructed (dynamic dispatch does not propagate down the inheritance hierarchy) and virtual calls (but not static calls) to pure virtual member functions are undefined behavior.

Reference members cannot be bound to temporaries in a member initializer list:

Note: same applies to default member initializer .

[ edit ] Initialization order

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

(Note: if initialization order was controlled by the appearance in the member initializer lists of different constructors, then the destructor wouldn't be able to ensure that the order of destruction is the reverse of the order of construction.)

[ edit ] Notes

[ edit ] example, [ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] References

  • C++23 standard (ISO/IEC 14882:2023):
  • 11.4.5 Constructors [class.ctor]
  • 11.9.3 Initializing bases and members [class.base.init]
  • C++20 standard (ISO/IEC 14882:2020):
  • 11.4.4 Constructors [class.ctor]
  • 11.10.2 Initializing bases and members [class.base.init]
  • C++17 standard (ISO/IEC 14882:2017):
  • 15.1 Constructors [class.ctor]
  • 15.6.2 Initializing bases and members [class.base.init]
  • C++14 standard (ISO/IEC 14882:2014):
  • 12.1 Constructors [class.ctor]
  • 12.6.2 Initializing bases and members [class.base.init]
  • C++11 standard (ISO/IEC 14882:2011):
  • C++98 standard (ISO/IEC 14882:1998):

[ edit ] See also

  • copy elision
  • converting constructor
  • copy assignment
  • copy constructor
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 15 May 2024, at 01:11.
  • This page has been accessed 2,801,054 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

COMMENTS

  1. Struct and union initialization

    When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99) initialize the struct members declared after the one initialized by the previous expression.

  2. c++

    typedef struct { int hour; int min; int sec; } counter_t; And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like: counter_t counter; counter = {10,30,47}; //doesn't work for 10:30:47. rather than

  3. How to Initialize Structures in C?

    In C, a structure (struct) is a user-defined data type that allows us to combine data items of different data types into a single unit. In this article, we will learn how to initialize structures in C. Initialize Structures in C. We can initialize the structure by providing the values of the members in the list during the declaration.

  4. How to Initialize a Struct in C

    In the main function, the createPerson function is used to initialize a Person struct named me. The subsequent printf statement displays the information stored in the me struct, showcasing the first name, last name, age, and alive status. Name: Jane Delaney. Age: 27. Alive: Yes.

  5. How to declare, initialize and access structures in C language

    Initialize structure using dot operator. In C, we initialize or access a structure variable either through dot . or arrow -> operator. This is the most easiest way to initialize or access a structure. Example: // Declare structure variable struct student stu1; // Initialize structure members. stu1.name = "Pankaj";

  6. Initializers (GNU C Language Manual)

    For numeric and pointer-type variables, the initializer is an expression for the value. If necessary, it is converted to the variable's type, just as in an assignment. You can also initialize a local structure-type (see Structures) or local union-type (see Unions) variable this way, from an expression whose value has the same type.

  7. C struct (Structures)

    You can create structures within a structure in C programming. For example, struct complex { int imag; float real; }; struct number { struct complex comp; int integers; } num1, num2; Suppose, you want to set imag of num2 variable to 11. Here's how you can do it:

  8. Initialization

    If the initialization of a non-inline variable (since C++17) is deferred to happen after the first statement of main/thread function, it happens before the first ODR-use of any variable with static/thread storage duration defined in the same translation unit as the variable to be initialized. If no variable or function is ODR-used from a given ...

  9. Initialize struct in C [3 ways]

    Structure initialization in C. C language offers us many ways to initialize a structure in our program. We can use the following initialization method to initialize struct: Initialization at Declaration. Initialization using Designated Initializer. Initialized at compile time using the dot (.) operator.

  10. struct (C programming language)

    A struct in the C programming language (and many derivatives) is a composite data type (or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the same address. The struct data type can contain other data types so is used for ...

  11. Brace initialization for classes, structs, and unions

    If a type has a default constructor, either implicitly or explicitly declared, you can use brace initialization with empty braces to invoke it. For example, the following class may be initialized by using both empty and non-empty brace initialization: C++. Copy. #include <string> using namespace std;

  12. Initialize and return a struct in one line in C++

    If you want your struct to remain a POD, use a function that creates it: Foo f = { a, b, c }; return f; return make_foo(1, 2, 3); With C++0x uniform initialization removes the need for that function: return Foo{1, 2, 3}; // or just: return {1, 2, 3}; @Cubbi: Right, good point - although i think i'll prefer the explicit version to avoid ...

  13. Inline Initialization

    The story is very different for static fields. In value types, static fields can be initialized inline. As you may have already guessed, such initialization does translate into the parameter-less static constructor initialization. For example, these two pieces of code are equivalent in the IL: struct NoInline { static int a = 5; }

  14. 13.8

    The key thing to understand at this point is that structs with only data members are aggregates. Aggregate initialization of a struct. Because a normal variable can only hold a single value, we only need to provide a single initializer: int x { 5 }; However, a struct can have multiple members: struct Employee { int id {}; int age {}; double ...

  15. Constructors and member initializer lists

    The only specifiers allowed in the declaration specifiers of a constructor declaration are friend, inline, constexpr (since C++11), consteval (since C++20), and explicit (in particular, no return type is allowed). Note that cv- and ref-qualifiers are not allowed either: const and volatile semantics of an object under construction only kick in after the most-derived constructor completes.

  16. LKML: Shigeru Yoshida: [PATCH v2] can: j1939: Initialize unused data in

    syzbot reported kernel-infoleak in raw_recvmsg() [1]. j1939_send_one() creates full frame including unused data, but it doesn't initialize it. This causes the kernel-infoleak issue.

  17. Convenient C++ struct initialisation

    Comment doesn't prevent initialization of the structure from being broken if I insert new field between foo and bar in the future. C would still initialize the fields we want, but C++ would not. And this is the point of the question - how to achieve the same result in C++.