Reputation: 47784
The following compiles successfully:
struct XX {
int element;
};
int main ()
{
XX XX, prev_XX ;
prev_XX = XX;
XX = prev_XX; // ??? NO error: expected unqualified-id before '=' token
}
How does compiler know whether it's a type or a variable?
Edit :
An error for this : (from sftrabbit's example)
int main ()
{
XX XX, prev_XX;
XX XX2; // error: expected ';' before 'XX2'
}
Upvotes: 1
Views: 111
Reputation: 110648
The variable name hides the struct name (§3.3.10):
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).
If you need to refer to the struct name specifically, you need to use an elaborated type specifier, struct XX
(§3.4.4):
An elaborated-type-specifier (7.1.6.3) may be used to refer to a previously declared class-name or enum-name even though the name has been hidden by a non-type declaration (3.3.10).
So the compiler knows that XX
refers to the variable here because that's all it can correspond to. It won't even consider the possibility of it referring to the struct. In fact, let's see what happens if we try to use it as a type:
struct XX {
int elemnent;
};
int main ()
{
XX XX, prev_XX;
XX XX2; // Can we continue to use XX as a type?
}
We actually get an error:
error: expected ‘;’ before ‘XX2’
So instead, we have to do struct XX XX2;
, which gives no error.
Upvotes: 10
Reputation: 299760
This is a subtle issue harking back to the days of C.
When you declare XX XX;
the second XX
(variable) shadows the first XX
(type). You can still access the type by using struct XX
to name it.
struct XX {};
int main() {
XX XX;
XX other; // error: expected ‘;’ before ‘other’
struct XX another; // OK
another = XX; // OK
return 0;
}
You can check it out here.
Upvotes: 1
Reputation: 310930
The name of the object hides the name of the structure. If you want to specify the structure you should use elaborated name for example
XX XX;
struct XX YY;
It was introduced in C++ because in C structure names and variables names belong to different name spaces due to the fact that in C you must always specify keyword struct with structures. In C++ it is allowed to use structure names without keyword struct but variable names hides structure names if they coinside.
Upvotes: 1
Reputation: 59997
It is due to the syntax of the expression.
Just like some words can be either a noun or verb - depends on the location in the sentence
Upvotes: 1