C Variables
1. What is a Variable?
-
A variable is a named memory location used to store data.
-
Each variable has:
-
Name (Identifier) → The name you give it.
-
Data Type → The type of data it can store (int, float, char, etc.).
-
Value → The actual data stored.
-
Example:
2. Rules for Naming Variables
-
Must start with a letter or underscore (
_). -
Can contain letters, digits, and underscores.
-
Cannot be a C keyword (like int, float, return).
-
Case-sensitive (
Age≠age).
Valid Examples:
Invalid Examples:
3. Variable Declaration and Initialization
(a) Declaration
-
Tells the compiler the type and name of a variable.
(b) Initialization
-
Assigns a value at the time of declaration.
-
You can also assign a value later:
4. Data Types of Variables
C has basic data types:
| Data Type | Memory Size | Example |
|---|---|---|
| int | 4 bytes | int age = 25; |
| float | 4 bytes | float pi = 3.14; |
| double | 8 bytes | double d = 3.14159; |
| char | 1 byte | char grade = ‘A’; |
-
int → Integer numbers
-
float → Decimal numbers
-
double → More precise decimal numbers
-
char → Single character
5. Multiple Variables Declaration
You can declare multiple variables of the same type in a single line:
6. Constants vs Variables
-
Variables → Value can change.
-
Constants → Value cannot change. Use
constkeyword.
7. Example Program Using Variables
Output:
8. Tips
-
Always choose meaningful names (
ageinstead ofa). -
Use consistent naming convention (like
snake_caseorcamelCase). -
Remember C is case-sensitive.
