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

I often see C ++ code as follows:

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

Why is a struct specifier needed? Is this really doing something? The compiler may already know that sockaddr declared as a structure, so I wonder why this is useful or necessary.

I tried to delete it in the past and did not notice a difference in behavior, but I'm not sure if it is safe to delete.

Similarly, what's the difference between the two?

 sizeof(struct sockaddr) sizeof(sockaddr) 
+4
source share
4 answers

As an β€œencoding” style, this is most likely a C legacy where a keyword is needed.

In C ++, this is not required in most situations, although it is sometimes used to force the compiler to resolve the name of the type name and not the name of any other entity (for example, 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 don’t think that a good style has a variable or function with the same name as the type, and I prefer to avoid using the struct keyword for this purpose in general, but the language allows this.

+5
source

This syntax comes from C, where it is required. In C ++, there is only one necessary use of this syntax

n3376 9.1 / 2

A class declaration introduces the class name into the scope in which any class, variable, function, or other declaration of that name is declared and hides in the scope (3.3). If the class name is declared in the area where a variable, function or enumerator with the same name is also declared, while both declarations are in the class, the class can only be assigned using the specified type specifier

 struct stat { // ... }; stat gstat; // use plain stat to // define variable int stat(struct stat*); // redeclare stat as function void f() { struct stat* ps; // struct prefix needed // to name struct stat stat(ps); // call stat() } 

+4
source

Code such as this comes directly from C (most likely by copying and pasting), where the struct keyword is required before any type name that is defined as a structure (unless you add the appropriate typedef statement). Using struct in this way is still supported in C ++ for backward compatibility, but since struct foo { ... }; in C ++, it automatically adds foo as a type name, (as a rule) it is safe to refer to the type later as soon as foo .

+1
source

You are basically right; in C ++, the struct keyword hardly matters when declaring a variable.

More than you wanted to know about this: using the struct keyword in a variable declaration in C ++

+1
source

Source: https://habr.com/ru/post/1487563/


All Articles