Reputation: 5195
To use a struct in a function outside of main(), can you use forward declaration and define it in main(), or does it have to be defined outside of a block?
Upvotes: 1
Views: 2348
Reputation: 70472
If you define a structure inside of main()
, it will hide the global name of the structure. So the function outside of main()
will only be able to reference the global name. This example is taken from the C++ 2011 draft, Section 9.1 p2:
struct s { int a; };
void g() {
struct s; // hide global struct s
// with a block-scope declaration
s* p; // refer to local struct s
struct s { char* p; }; // define local struct s
struct s; // redeclaration, has no effect
}
There is no syntax to refer to the locally defined type from outside the function scope. Because of that, even using a template will fail, because there is no way to express the instantiation of the template:
template <typename F> void bar (F *f) { f->a = 0; }
int main () {
struct Foo { int a; } f = { 3 };
bar(&f); // fail in C++98/C++03 but ok in C++11
}
Actually, this is now allowed in C++11, as explained in this answer.
Upvotes: 4