Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are some local type declarations prefixed with 'struct' in C++

Tags:

c++

struct

I often see C++ code like this:

void foo()
{
  struct sockaddr* from;
  // ...
}

Why is the struct specifier needed? Does it actually do anything? The compiler can already know that sockaddr is declared as a struct, so I wonder why this is useful or necessary.

I've tried removing it in the past and haven't noticed a difference in behaviour, but I'm not confident it's safe to remove.

Similarly, what's the difference between these two?

sizeof(struct sockaddr)
sizeof(sockaddr)
like image 756
Drew Noakes Avatar asked Dec 20 '22 04:12

Drew Noakes


1 Answers

As a coding "style", this is most likely a heritage of C, where the keyword is necessary.

In C++ this is not needed in most situations, although it is used sometimes to force the compiler to resolve a name to the name of a type rather than the name of some other entity (like a variable, as in the following example):

struct x
{
};

int main()
{
    int x = 42;
    struct x* pX = nullptr; // Would give a compiler error without struct
}

Personally, I do not consider good style having a variable, or a function with the same name as a type, and I prefer avoiding having to use the struct keyword for this purpose at all, but the language allows it.

like image 118
Andy Prowl Avatar answered Dec 24 '22 01:12

Andy Prowl