0

In C++, when we declare a variable, we can do

A a;

Where A is a class name. But in some cases, we add "struct" before the class name.

struct sockaddr_in addr_serv;  

Is the "struct" here necessary? why?

user2994219
  • 125
  • 3
  • If a struct and a function have the same name, the `struct` adjective differentiates. – Eljay May 25 '22 at 01:33
  • In C++ it is not necessary, it is optional (except in some specific cases). In C, it is necessary (although can be avoided using an additional `typedef`) because the type is actually `struct sockaddr_in` not `sockaddr_in`. When writing code that uses a C header (such as posix sockets headers, as in your case) a lot of available sample code is written in C, even though usable in C++ - so we end up with C++ code using that approach. – Peter May 25 '22 at 01:35

0 Answers0