Reputation: 51
hi all i just wanted to know whether we can declare variable name as structure name.
for example
typedef struct
{
char c;
}t;
then in some function can i use
fun()
{
t t;
}
is this valid? if so then how compiler differentiate between them?
Upvotes: 3
Views: 1894
Reputation: 65496
yes because each thing lives in a different place in the compilers understanding.
t t;
The compiler is expecting a type when it encounters the first t and it has a type called t.
Edit: To address comments.
I'm not talking about scope.
But since I've not written a compiler (only interpreters) I don't know the term. The compiler is expecting a token at the first t to be a type, it also knows what type have been declared up to that point. Since it see a name that refers to a type it's happy. Whereas if a token that wasn't a type was found there then it would rightly signal an error.
Upvotes: 0
Reputation: 1868
parser first gets the data type and maintains a different table and later part as the variable name. So it works absolutely.
Upvotes: 0
Reputation: 6233
Yes, but why would you want to? If you want bugs and errors to thrive in your project, then go right ahead and name variables after types.
Upvotes: 3
Reputation: 92864
fun() { t t; }
is this valid ?
No it is not. Return type of fun()
is missing and implicit int
return type is deprecated.
However void fun(){ t t ;}
is syntactically valid.
Upvotes: 1
Reputation: 70701
Yes, it is valid. If you do that, then the structure type is hidden in the enclosing scope and t
refers only to the declared variable.
Upvotes: 3