Reputation: 53
there is a line in c code:
struct name_1 name2;
what this line implies?
my understanding about above line is name_1 is the name of the structure and name2 is the object variable. However name_1 should have been defined somewhere, but I could not find the definition of name_1.
so my question is; is there anything like this where we can have an object of a structure which is not defined anywhere.
Upvotes: 0
Views: 204
Reputation: 66
Is there a header file (name.h) you have included in your c code? Usually, structure, constant and function declarations are in the header file, which is 'included' (at the top of your c file), and you could then use those structures and constants in your c file without defining them
Upvotes: 0
Reputation: 141648
At file scope, this is the definition of a variable called name2
whose type is struct name_1
. If there has not been a previous declaration of struct name_1;
then this line also declares that type.
Being a file scope variable definition with no initializer nor storage class specifier, this is a tentative definition. Tentative definitions may have incomplete type so long as the type is completed by the end of the file, e.g.:
#include <stdio.h>
struct foo bar;
void f();
int main()
{
printf("%p\n", (void *)&bar);
f();
// cannot do this
// printf("%d\n", bar.x);
}
struct foo { int x; };
void f()
{
bar.x = 5;
}
This sort of code would be uncommon however. If you see struct foo bar;
in real code it is more likely that struct foo
was previously defined somewhere that you are overlooking.
Upvotes: 2