C-Program
Variables and Data Types in C
Last Updated on: 4th Jul 2025 20:54:08 PM
In C programming, variables are used to store data temporarily in memory, and data types define what kind of data a variable can hold — such as integers, floating-point numbers, characters, etc.
1. What is a Variable?
A variable is a named memory location that stores a value which can be changed during program execution.
Rules for Naming Variables (Identifiers):
-
Must start with a letter (A–Z or a–z) or an underscore
_
-
Cannot start with a digit (e.g.,
1total
?) -
Cannot be a keyword (e.g.,
int
,return
) -
Should be meaningful and readable
2. Variable Declaration and Initialization
Declaration:
Before using a variable, you must declare it by specifying its data type.
int age; // Declares an integer variable named 'age'
Initialization:
Assigning a value at the time of declaration.
int age = 25; // Declares and initializes 'age' with 25
You can also assign values later:
int age;
age = 25;
3. Data Types in C
Data Type | Description | Size (on most systems) | Format Specifier |
---|---|---|---|
int |
Stores integers (whole numbers) | 4 bytes | %d |
float |
Stores decimal numbers | 4 bytes | %f |
double |
Stores large decimal numbers (higher precision) | 8 bytes | %lf |
char |
Stores a single character | 1 byte | %c |
void |
Represents no value (used in functions) | 0 bytes | — |
Examples:
int age = 30; // Integer
float price = 99.99; // Decimal number
char grade = 'A'; // Character
Multiple Variable Declaration:
int x = 10, y = 20, z = 30;
4. Type Conversion and Type Casting
Sometimes you need to convert one data type into another, either automatically or manually.
a. Implicit Type Conversion (Automatic)
C automatically converts lower data types to higher to prevent data loss.
int a = 10;
float b = a; // int is automatically converted to float
Here, a becomes 10.0 and is stored in b.
b. Explicit Type Casting (Manual Conversion)
You can manually convert one data type to another using casting syntax:
float x = 5.5;
int y = (int) x; // x is cast to int, value becomes 5
Print Now
printf("x = %f, y = %d", x, y);
Output:
printf("x = %f, y = %d", x, y);
Example Program:
#include <stdio.h>
int main() {
int a = 10;
float b = 3.5;
float result = a + b; // Implicit conversion
printf("Result: %.2f\n", result);
int x = (int)b; // Explicit conversion
printf("After casting b to int: %d", x);
return 0;
}
Quick Summary :
Concept | Description |
---|---|
Variable | A named memory location that holds data |
Data Type | Defines the type of data a variable can store |
Declaration | Tells the compiler to reserve memory |
Initialization | Assigns a value to a variable |
Implicit Conversion | Auto-conversion by compiler |
Explicit Casting | Manual conversion using (type) syntax |