Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an explicit cast necessary in the following struct definition

With struct initialization via a compound literal, it will do the casting itself. For example:

struct movie {
    char title[50];
    int year;
};
typedef struct movie Item;

typedef struct node {
    Item        item;
    struct node *next;
} Node;

typedef struct linkedlist {
    Node   *head;
    size_t size;
} LinkedList;
LinkedList movies2 = {
    .head=&(Node){{"Avatar", 2010}, NULL},
    .size=1
};

However, if I separate the definition, I have to add in an explicit cast:

LinkedList movies2;
movies2 = (LinkedList) {
    .head=&(Node){{"Avatar", 2010}, NULL},
    .size=1
};

Code: https://godbolt.org/z/dG8nMh

And if I leave out the (cast_type) in the second one I will get an error along the lines of error: expected expression before ‘{’ token. Why is this so?

That is, why does the initialization not need the cast but the other definition does? My thought was the second version should be able to resolve itself without the explicit cast but obviously that is incorrect.

like image 390
David542 Avatar asked Mar 10 '21 19:03

David542


People also ask

Why do we need explicit type casting?

A cast, or explicit type conversion, is special programming instuction which specifies what data type to treat a variable as (or an intermediate calculation result) in a given expression. Casting will ignore extra information (but never adds information to the type being casted).

What is the meaning of explicit type casting?

Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.

What is explicit cast in C?

Explicit Type casting − This conversion is done by user. This is also known as typecasting. Data type is converted into another data type forcefully by the user. Here is the syntax of explicit type casting in C language, (type) expression.

How do you know if an explicit object casting is needed?

Narrowing Casting (larger to smaller type)When we are assigning a larger type to a smaller type, Explicit Casting is required.


Video Answer


3 Answers

In the both cases you are using compound literals.

In the first case in the declaration

LinkedList movies2 = {
    .head=&(Node){{"Avatar", 2010}, NULL},
    .size=1
};

you are using the compound literal (Node){{"Avatar", 2010}, NULL} of the type Node in the initializer list the address of which is used as an initializer for the data member head of the structure LinkedList.

In the second case you at first created an object of the type LimkedList

LinkedList movies2;

and then you are using the assignment operator to the created object with the compound literal of the type LinkedList

(LinkedList) {
    .head=&(Node){{"Avatar", 2010}, NULL},
    .size=1
}

that is

movies2 = (LinkedList) {
    .head=&(Node){{"Avatar", 2010}, NULL},
    .size=1
};

That is there are no any casting. There are used two different compound literals. One of the type Node and other of the type LinkedList.

To make it clear. Consider a simple example

int x = { 10 };

in the declaration above the variable x is initialized by the integer constant 10.

You can write also the following way

int tmp = { 10 };
int x;
x = tmp;

Here there is created an intermediate variable to initialize the variable x. A compound literal in fact is an unnamed object. The code above may be rewritten like

int x;
x = ( int ){ 10 }; 

Here there is no any casting. This expression ( int ){ 10 } creates an unnamed object of the type int that is initialized by the integer constant 10. And this newly created unnamed object is assigned to the variable x.

See also the following question What are the advantages of using “{}” for casting in C Language?

like image 98
Vlad from Moscow Avatar answered Oct 23 '22 11:10

Vlad from Moscow


The other answers have covered the difference between initialization and assignment from a compound literal. There's another conceptual point that needs to be brought up however:

LinkedList movies2 = {
    .head=&(Node){{"Avatar", 2010}, NULL},
    .size=1
};

In either case, you're creating a linked list and setting the head to point to a node that is not dynamically allocated nor part of some application defined pool. Members of a linked list are typically either created dynamically via malloc or taken from a pool.

What you have now is one node of the list that is "special" in that it hasn't been added to the list the way other nodes would have been added, meaning you would need extra logic to keep track of it and handle it differently from other nodes in the list if it were removed.

It would be better to initialize the head of the list to NULL. Then your add / delete functions would need to know whether or not the list is empty.

like image 1
dbush Avatar answered Oct 23 '22 13:10

dbush


What appears to be an explicit cast is part of the compound literal semathics (type_name){ }.

The syntax of a compound literal can be confused with a typecast, however a cast is a non-lvalue expression whereas a compound literal is an lvalue.

C11 N1570 §6.5.2.5

Semantics

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

The first one is an initializer, not an assignment, so doesn't need it.


I would also note that in the expression .head = &(Node){{"Avatar", 2010}, NULL} the compound literal being an lvalue, can be taken by address, but its lifetime is limited to the scope where it belongs, accessing it outside that scope invokes undefined behavior, i.e.:

LinkedList getLinkedList()
{
    LinkedList movies2;
    movies2 = (LinkedList){
        .head = &(Node){{"Avatar", 2010}, NULL},
        .size = 1};       
    return movies2;
}
LinkedList l = getLinkedList();
printf("%s", l.head->item.title); // undefined behavior
like image 1
anastaciu Avatar answered Oct 23 '22 13:10

anastaciu