a. Variable declaration

User-Defined Type Declaration

In C programming, a feature known as “type definition” is available which allows a programmer to define an identifier that represents an existing data type. The user defined identifier can be used later in the program to declare variables. The general syntax of declaring a variable by user-defined type declaration is:

typedef type identifier;

Here, type is an existing data type and identifier is the “new name” given to the data type. Here, the new type is ‘new’ only in name but not the data type.

Note: typedef cannot create a new type

Consider an example:

typedef int age;
typedef float weight;

Here, age represents int and weight represent float which can be used later in the program to declare variables as follows:

age boy1,boy2;
weight b1,b2;

Here, boy1 and boy2 are declared as as integer data type and b1 & b2 are declared as floating integer data type.

The main advantage of using user-defined type declaration is that we can create meaningful data type names for increasing the readability of a program.

Another user-defined data type is enumerated data type. The general syntax of enumerated data type is:

enum identifier {value 1,value 2,...value n};

Here, identifier is a user-defined enumerated data type which can be used to declare variables that can have one of the values enclosed within the braces. The values inside the braces are known as enumeration constants. After this declaration, we can declare variables to be of this ‘new’ type as:

enum identifier v1, v2, ... vn;

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


User-defined Type Declaration Example

enum mnth {January, February, ..., December};
enum mnth day_st, day_end;
day_st = January;
day_end = December;
if (day_st == February)
day_end = November;

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

For example:

enum mnth {January = 1, February, ..., December};

Here, the constant January is assigned value 1. The remaining values are assigned values that increase successively by 1.

The definition and declaration of enumerated variables can be combined in one statement. For example;

enum mnth {January, ... December} day_st, day_end;

Leave a Reply

Your email address will not be published. Required fields are marked *