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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With