-1

I was reading some code and came across the following statement:

 struct sockaddr_in server

I understand that sockaddr_in is some predefined struct but why do we put struct as a prefix? Also shown below, a similar thing is attempted

enter image description here

Cannot I just write:

sockaddr_in server
Amanda
  • 2,013
  • 3
  • 24
  • 57

2 Answers2

6

The syntax of the C language requires that a declaration of a variable of a struct type include the struct keyword before the type.

While C++ does allow this keyword to be omitted, C does not.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

In C there is such a notion as a tag of a structure, union or enumeration. Correspondingly an identifier can denote a tag. To distinguish such an identifier from an identifier of other variable identifiers that denote tags are used together with keywords struct, union, and enum.

For example consider the following demonstrative program.

#include <stdio.h>

int main(void) 
{
    struct x
    {
        int x;
    } x = { 10 };

    printf( "x.x = %d\n", x.x );

    return 0;
}

Its output is

x.x = 10

Here the same name x is used to denote a structure tag, a member of a structure and a variable of a structure type.

In C++ there is used the term class name the same way as a name of any other entity. In C++ there are name spaces that allows to place entities with the same name in different name space to avoid a collision.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335