C Programming Structure,Unions & Enum

0

Structure in C Programming

If we declare lots of variable under a name, then that is the structure.  The variables might be int,char,float or pointers. To define a structure in C language we need to use struct keyword and unique tag name. The syntax of struct is:

An structure variables can be primitive or aggregate like array.

 

Structure is not a variable. Defining an structure mean, creating new data type. We also can declare variable that type of structure:

Here the variable var1 and var2(Separated by commas) working different variable of the same data type testTag. testTag is not required if variables declared. To access variables inside struct we need to use dot operator. And to access pointer we need minus(-) and grater than(>) which become ->. Below an example given!

 

Let’s see the usage of struct:

  1. In line 3-8 i am defining structure and it’s variables. Here the struct is the keyword and testTag is called tag.
  2. In line 11 we tell the compiler that it is the variable of struct type and in line 12 pointer of struct type.
  3. In line 13-15 the struct variable initialized. For normal variable we need to access variable using (dot) operator as did in line 13-15.
  4. In line 16 reference to type of the struct type(variable) so that we can access the pointer inside.
  5. Line 18 printf() function called. And printf function access the struct variables with dot operator. To access the pointer more two operator used is minus(-) and grater than(>).

 

Union Example

Union is same as struct but only difference is we can’t use all variables at once like we can in structure.

 

To be continued…..