Variables in C
Variables are like containers that store data values in your program. Think of them as labeled boxes where you can put different types of information and retrieve them later when needed.
The value stored in a variable can be changed during program execution, which is why it's called a "variable."
Variable Declaration
Before using a variable in C, you must declare it. This tells the compiler what type of data the variable will store and what name you'll use to refer to it.
Syntax:
data_type variable_name;
Example:
int age; // Declares an integer variable named 'age'
float price; // Declares a floating-point variable named 'price'
char grade; // Declares a character variable named 'grade'
Variable Initialization
You can assign a value to a variable when you declare it (initialization) or later in your program.
Initialization during declaration:
int age = 25;
float price = 99.99;
char grade = 'A';
Initialization after declaration:
int age;
age = 25;
Common Data Types for Variables
| Data Type | Description | Example |
|---|---|---|
| int | Integer numbers | int count = 10; |
| float | Decimal numbers (single precision) | float temperature = 36.5; |
| double | Decimal numbers (double precision) | double pi = 3.14159; |
| char | Single character | char initial = 'J'; |
Variable Naming Rules
- Variable names must start with a letter (a-z, A-Z) or underscore (_)
- Can contain letters, digits, and underscores
- Cannot contain spaces or special characters
- Cannot be a C keyword (like
int,float,if, etc.) - Case-sensitive (
ageandAgeare different variables)
Valid variable names:
int student_age;
float _price;
char firstName;
int count2;
Invalid variable names:
int 2count; // Cannot start with a digit
float student-age; // Cannot contain hyphen
int float; // Cannot use C keywords
Printing Variables
To print the value of a variable in C, we use the printf function from the stdio.h library. Each data type has its own format specifier:
%d → for int
%f → for float
%c → for char
%lf → for double
Complete Example
Here's a simple program demonstrating variable usage:
#include <stdio.h>
int main() {
// Variable declarations and initializations
int students = 30;
float average_score = 85.5;
char section = 'A';
// Using variables
printf("Section %c has %d students\n", section, students);
printf("Average score: %.1f\n", average_score);
// Modifying variable values
students = 32;
printf("Updated student count: %d\n", students);
return 0;
}
Output:
Section A has 30 students
Average score: 85.5
Updated student count: 32
Variables are fundamental building blocks in C programming. They allow you to store, manipulate, and retrieve data throughout your program's execution!