Friday, 24 January 2014

Tag name in structure

No comments:
Tag name in struct is one which is the name of the struct we are giving while creating the struct. For instance, in the following declaration

struct s

s is the tag name. Some will misunderstood s as type name. Here s  is not a type name they are actually tag names. They are also like a normal identifiers in c.

The following usage is wrong in c code,
s var1;   // Wrong Declaration
struct s var1; //Correct Declaration

Although they are name of the structures we cannot create the variable by just calling them. You need to use the struct keyword while using that identifier.

The process of calling the struct s var1 is called as elaborated type specifier.
The enums, union also fall under same category. The name of the enum or union cannot be used separately, they have called with their keywords such as struct, enum;

You will wonder sometimes, that why programmers always use a typedef in the struct keyword. This is because, writing
struct s
struct s member1;
is equal to
typedef struct  s
s_ref member1;

If we fail to use the typedef and in order to use the struct in future, we need to specify struct keyword often. So we are using the typedef in struct programs.


The normal identifiers cannot be used like this
int flag;
void flag();

Compiler throws error at second declaration. But in family that uses the tag names  can have the same name as identifier.
struct s {};  //valid
enum s{};    //valid
union s{};    //valid

This is because they are referred using the keyword. C stores this identifier in a different table.
And even the following cases also is valid

int s;
struct s{};

1.USE OF elaborated type specifier:
In C, it is compulsory to use a elaborated type specifier for using the struct, union, and enums.
So are you wonder what is elaborated type specifier am I correct?


While creating the object for the struct , you need to use a struct keyword along with the type name. (strcut s obj;) here struct is keyword s is typename obj is object. This process of creating the object using type name and their corresponding keyword is called as elaborated type specifier.
i.e, we cannot use like following,
struct s
s obj;// Invalid in c, but valid in c++

Finally, In C we have to use ( struct s {} as struct s obj; ) and in c++ (s obj; )But using elaborated type specifier is also valid in c++.(struct s obj)

In similar to the above discussion, in c++ we are using class c{} as c obj;

No comments:

Post a Comment