Reputation: 73
I have declared two different structures with same name foo, as one of them is declared as globally, and can be easily accessible by any function in program. But I have this second struct in main, which is locally declared.
Worst comes worst I need to access both of them in main? I did it by declaring struct variable with different names. But now the problem is I need to check size of structures... How should I get the size of local struct not a global one?
#include <stdio.h>
#include <stdlib.h>
struct foo {
char arr1[200];
int x_val;
int y_val;
float result;
};
struct foo globe_foo;
int main()
{
struct foo {
char c;
char arr[20];
int x;
};
struct foo my_foo;
globe_foo.x_val = 20;
printf("Globe foo x_val: %d\n",globe_foo.x_val);
printf("Size of struct foo is: %d\n",sizeof(struct foo));
//how to check size of global decleared stuct foo?
printf("Size of struct foo is: %d\n",sizeof(struct foo));
system("pause");
return 0;
}
Upvotes: 1
Views: 675
Reputation: 222900
Standard C does not provide any way to refer to an identifier (either object name or type name) that is hidden by a local declaration.
In this case, you can see the size of the global struct foo
by using the size of the object, sizeof globe_foo
.
GCC (and compilers supporting its extensions) provides a way to refer to the type of an object, __typeof__
. So, in GCC, you can refer to the type of globe_foo
with __typeof__(struct globe_foo)
.
Another option is to give the global type an alias, with typedef
. If, at file scope, you declare typedef struct foo foo_t;
, then the type foo_t
will be visible inside a function even when struct foo
is hidden.
When printing sizes (values of type size_t
), you should use a %zu
specification with printf
, not %d
.
Upvotes: 1
Reputation: 2176
Variables within block scope whose name is same as the global scope hides the global identifier
ISO C9899 in 6.2.1 says:
If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will be a strict subset of the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.
So here the global struct foo
is hidden totally(as if its not there) if you just refer to the typename inside the main()
.
Suggestions : use different names or use variables with different names for these types or typedef the struct types.
Your printf("Size of struct foo is: %d\n",sizeof(struct foo));
will give the size of only local struct foo(28 or 25 depends).
Upvotes: 2