Chapter 2.4 - Discuss How Variables Are Used In A Program | Part - 2


User-Defined Type Declaration


C supports a feature known as "type definition" that allows users to define an identifier that would represent an existing data type. The user-defined data type identifier can later be used to declare variables. It takes the general form. 

typedef type identifier;
Where type refers to an existing data type and "identifier" refers to the 'new" name given to the data type. The existing data type may belong to any class of type, including the user-defined ones. Remember that the new type is 'new' only in name, but not the data type. typedef cannot create a  new type. Some examples of type definition are:

typedef int units;     
typedef float marks;

Here, units symbolize int and marks symbolizes float. They can be later used to declare variables as follows:

units batch1, batch2;               

batch1 and batch2 are included as int variable and name1[50] and name2[50] are declared as 50 element floating point array variables. The main advantage of typedef is that we can create meaningful data type names for increasing the readability of the program.
Another user-defined data type is an enumerated data type provided by ANSI standard. It is defined as follows: 

enum identifier {value1, value2....valuen};

The "identifier" is a user-defined enumerated data type which can be used to declare variables that have one of the values enclosed within in braces (known as enumeration constants). After this definition, we can declare variables to be of this 'new' type as below:

enum identifier v1, v2,....vn;

The enumerated variables v1,v2....vn can only have one of the values value1, value2,...valuen. The assignments of the following types are valid:


v1 = value3;
v5 = value1;

An example:

enum day {monday, Tuesday,...Sunday};
enum day week_st, week_end;                 
week_st = Monday;                                   
week_end = Friday;                                   
if(week_st == Tuesday)                              
week_end = saturday;                                   

The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants. That is, the enumeration constant value 1 is assigned 0, value2 is assigned 1, and so on. However, the automatic assignments can be overridden by assigning values explicitly to the enumeration constants.



             C Programming Star Pattern Programs     

For example:


enum day {Monday = 1, Tuesday,....Sunday};

Here, the constants Monday is assigned the value of 1. The remaining constants are assigned values that increase successively by 1.
The definition and declaration of enumerated variables can be combined in one statement.

Example:

enum day {Monday,......Sunday} week_st, week_end;


Post a Comment

4 Comments

Ask Me Everything About Programming.