In C, when do structure names have to be included in structure initializations and definitions?

Posted by Tyler on Stack Overflow See other posts from Stack Overflow or by Tyler
Published on 2013-10-19T03:52:09Z Indexed on 2013/10/19 3:53 UTC
Read the original article Hit count: 138

Filed under:
|
|

I'm reading The C Programming Language by K&R and in the section on structures I came across these code snippets:

struct maxpt = { 320, 200 };

and

/* addpoints: add two points */
struct addpoint(struct point p1, struct point p2)
{
    p1.x += p2.x;
    p1.y += p2.y;
    return p1;
}

In the first case, it looks like it's assigning the values 320 and 200 to the members of the variable maxpt. But I noticed the name of the struct type is missing (shouldn't it be "struct struct_name maxpt = {320, 200}"? In the second case, the function return type is just "struct" and not "struct name_of_struct".

I don't get why they don't include the struct names - how does it know what particular type of structure it's dealing with? My confusion is compounded by the fact that in previous snippets they do include the structure name, such as in the return type for the following function, where it's "struct point" and not just "struct". Why do they include the name in some cases and not in others?

/* makepoint: make a point from x and y components */
struct point makepoint(int x, int y)
{
    struct point temp;
    temp.x = x;
    temp.y = y;
    return temp;
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about struct