David542
David542

Reputation: 110502

Difference between two struct initializations

What is the difference between the following two initializations for a Struct?

Car ford = {
    .name = "Ford F-150",
    .price = 25000
};

And:

Car dodge = (Car) {
    .name = "Ram",
    .price = 1000
};

From Compiler Explorer, it looks like the two produce the same code:

enter image description here


What does the (StructName) do when preceding the struct? It seems its necessary when doing complex initializations such as:

CarPtr mazda = & (Car) {
    .name = "Mazda",
    .price = 20000
};

Also related, to the two answers from Possible to initialize/assign a struct pointer?.

Upvotes: 2

Views: 195

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

In this declaration

Car dodge = (Car) {
    .name = "Ram",
    .price = 1000
};

there are created two objects of the type Car. The first one is the unnamed compound literal

(Car) {
    .name = "Ram",
    .price = 1000
}

that is used to initialize another named object dodge.

From C Standard (6.5.2.5 Compound literals)

3 A postfix expression that consists of a parenthesized type name followed by a braceenclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

In fact it is similar to the following declarations

Car ford = {
    .name = "Ford F-150",
    .price = 25000
};

Car dodge = ford;

The difference is that in the last example we created one more named object.

From the C Standard (6.7.9 Initialization)

13 The initializer for a structure or union object that has automatic storage duration shall be either an initializer list as described below, or a single expression that has compatible structure or union type. In the latter case, the initial value of the object, including unnamed members, is that of the expression.

Upvotes: 3

Related Questions