Variables in C
What is variable in C?
Variables in C: A variables are used to store data values that can be manipulated and accessed throughout the program. Each variable in C has a specific data type which defines what kind of data it can hold (e.g., integer, character, floating-point number, etc.). Here are some common variable types in C along with examples:
Different Types of Variables in C
Integer Variables (int
): Used to store whole numbers (both positive and negative) without decimal points.
int age = 30;
In this example, age
is a variable of type int
that stores the value 30
.
Character variable in C
Character Variables (char
): Used to store single characters (letters, digits, special symbols) enclosed in single quotes. But if you want to store multiple characters in a variable, you need to declare a character array variable. We shall discuss it in separate article.
char grade = 'A';
Here, grade
is a variable of type char
storing the character 'A'
.
Floating variable in C
Floating-point Variables (float
and double
): Used to store numbers with decimal points. float
is a single-precision floating-point type, while double
is a double-precision floating-point type which provides more precision.
float pi = 3.14;
double largeNumber = 123456.789;
In these examples, pi
is a float
variable storing 3.14
, and largeNumber
is a double
variable storing 123456.789
.
Boolean Variable in C
Boolean Variables (bool
): Used to store true or false values.
#include <stdbool.h>
bool isReady = true;
Here, isReady is a bool variable set to true.
Array Variable in C
Arrays: Variables that can hold multiple values of the same data type. Elements in an array are accessed using an index.
int numbers[5] = {1, 2, 3, 4, 5};
numbers
is an array of int
type with 5 elements.
Pointer Variable in C
Pointer Variables (*
): Variables that store memory addresses. Pointers are used for dynamic memory allocation and advanced data structures.
int *ptr;
int num = 10;
ptr = # // ptr now holds the address of num
Here, ptr
is a pointer variable that can hold the address of an int
.
Structure Variable in C
Structures (struct
): Variables that can hold different data types grouped together under a single name.
struct Person {
char name[50];
int age;
float salary;
};
struct Person employee;
employee.age = 30;
employee
is a structure variable of type struct Person
storing information about a person.
These are some of the fundamental variable types in C. Understanding these types helps programmers choose appropriate storage for their data and write efficient and clear code.