C Data Types
Data types are an essential part of any programming language and they define the type of data a variable can hold. In C, data types can be divided into three main categories:
- Basic data types
- Derived data types
- User-defined data types
Let's explore each category in detail:
Basic Data Types:
Basic data types are the fundamental data types that are available in C. They are:
-
int
: This data type is used to store integers, such as -1, 0, 1, 2, etc. The size of anint
varies depending on the platform, but it's usually 2 or 4 bytes. Example:1int x = 10;
-
float
: This data type is used to store floating-point numbers, such as 1.0, 2.5, 3.14, etc. The size of afloat
is 4 bytes. Example:1float y = 3.14;
-
double
: This data type is used to store double-precision floating-point numbers. The size of adouble
is 8 bytes. Example:1double z = 3.14159265358979323846;
-
char
: This data type is used to store a single character, such as 'a', 'b', 'c', etc. The size of achar
is 1 byte. Example:1char ch = 'A';
-
short
: This data type is used to store small integers. The size of ashort
is 2 bytes. Example:1short s = 32767;
-
long
: This data type is used to store large integers. The size of along
is 4 bytes. Example:1long l = 2147483647;
Derived Data Types:
Derived data types are data types that are derived from basic data types. They are:
-
array
: This data type is used to store a collection of values of the same data type. Example:1int a[5] = {1, 2, 3, 4, 5};
-
pointer
: This data type is used to store the address of a variable. Example:1int x = 10, *p; 2p = &x;
-
structure
: This data type is used to store a collection of variables of different data types. Example:1struct student { 2 int roll; 3 char name[20]; 4 float marks; 5};
-
union
: This data type is used to store a collection of variables of different data types, but only one of them can be stored at a time. Example:1union data { 2 int x; 3 float y; 4};
User-Defined Data Types
C also allows you to define your own data types. This can be done using the typedef
keyword, which creates an alias for an existing data type. For example, you can create a new data type distance
that is an alias for float
:
1typedef float distance;
This allows you to use distance
as a new data type in your program, like so:
1distance distance_run = 10.5;
Another way to create user-defined data types is through the use of structures. A structure is a collection of variables of different data types, grouped together under a single name. For example, you can create a structure to represent a point in two-dimensional space:
1struct point { 2 int x; 3 int y; 4};
You can then create variables of this new data type struct point
, like so:
1struct point p1; 2p1.x = 10; 3p1.y = 20;
By using user-defined data types, you can make your code easier to read and understand, and increase its overall structure and organization.