in C
struct node {
int x;
};
node *y; // incorrect
struct node *y; // correct
in C++
struct node{
int x;
};
node *y; // correct
y = new node; // correct
Question: Why is the tag name acceptable to create a pointer in C++ not in C?
Because the C++ standard says so, and the C standard doesn't.
I would say that C++ made the change to make classes easier to use (remember, classes and structs are fundamentally the same thing in C++; they only differ in default visibility), and C didn't follow suit because that would break tons of existing C code.
The reason is not just because the standard says so, C++ actually has namespaces while the struct
keyword allowed for a primitive form of namespace in C which allowed you to have a struct and a non-struct identifier with the same name. We can see this primitive form of a namespace from the C99 draft standard section 6.2.3
Name spaces of identifiers which says:
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:
and has the following bullets:
— label names (disambiguated by the syntax of the label declaration and use);
— the tags of structures, unions, and enumerations (disambiguated by following any24) of the keywords struct, union, or enum);
— the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
I could make up an example but POSIX gives us a great example with stat which is both a function and a struct :
int stat(const char *restrict path, struct stat *restrict buf);
^^^^ ^^^^^^^^^^^
If you want to write the way node* y in C, just
typedef struct node {
int x;
} node;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.