Variables, Constants & Data Types
Learn how to store and manipulate data in C. Understanding variables, types, and memory.
đ¯ What is a Variable?
A variable is like a labeled box in your computer's memory where you can store data. Just like you might have a box labeled "Age" that contains a number, C variables have:
đĄ Three Things Every Variable Needs
- Name (Identifier): What you call the variable (e.g., age, salary)
- Type: What kind of data it stores (number, text, decimal)
- Value: The actual data stored inside
đī¸ Memory Visualization
âââââââââââââââââââââââââââââââââââââââââââââââââââ
â Memory Address Variable Name Value â
âââââââââââââââââââââââââââââââââââââââââââââââââââ¤
â 0x1000 age 25 â
â 0x1004 salary 50000.50 â
â 0x1008 grade 'A' â
â 0x100C pi 3.14159 â
âââââââââââââââââââââââââââââââââââââââââââââââââââ
đ Declaring Variables
Before using a variable, you must declare it - tell C what type it is and what you'll call it.
Basic Syntax
data_type variable_name; // Declaration only
data_type variable_name = value; // Declaration + Initialization
#include <stdio.h>
int main() {
// Step 1: Declare variables (reserve memory)
int age; // Integer - whole numbers
float salary; // Float - decimal numbers
char grade; // Character - single letter/symbol
double pi; // Double - more precise decimals
// Step 2: Assign values (store data)
age = 25;
salary = 50000.50;
grade = 'A';
pi = 3.14159265359;
// Or do both at once (preferred)
int count = 10;
float price = 99.99;
char initial = 'J';
// Step 3: Use the variables
printf("Age: %d years\n", age);
printf("Salary: $%.2f\n", salary);
printf("Grade: %c\n", grade);
printf("Pi value: %.10f\n", pi);
return 0;
}
đ Line-by-Line Explanation
int age;- Reserves memory for a whole number, calls it "age"age = 25;- Puts the value 25 into that memory locationprintf("%d", age);- Reads the value from memory and prints it
Rules for Variable Names
â Valid Names
age,salary,count2_total,student_nametotalAmount(camelCase)
â Invalid Names
2count- Cannot start with numbertotal amount- No spaces allowedfloat- Cannot use keywords$price- $ not allowed
â ī¸ Common Mistake: Uninitialized Variables
int main() {
int x; // x contains GARBAGE value!
printf("%d", x); // Unpredictable output
int y = 0; // â
Always initialize!
printf("%d", y); // Output: 0
}
Best Practice: Always initialize variables when you declare them!
đ Data Types in C
C is a strongly typed language. Every variable must have a type that tells the compiler:
- How much memory to reserve
- What kind of operations are valid
- How to interpret the stored bits
Basic Data Types
| Type | Description | Size | Format | Example Values |
|---|---|---|---|---|
char |
Single character or small integer | 1 byte | %c or %d | 'A', 'z', '9', '$' |
int |
Whole numbers (integers) | 4 bytes | %d | -42, 0, 999999 |
float |
Decimal numbers (single precision) | 4 bytes | %f | 3.14, -0.5, 99.99 |
double |
Decimal numbers (double precision) | 8 bytes | %lf | 3.14159265359 |
đ¤ What do the sizes mean?
- 1 byte = 8 bits (8 zeros/ones)
- More bytes = Can store larger values or more precision
int: 4 bytes = 32 bits = ~Âą2 billion rangedouble: 8 bytes = More decimal places thanfloat
Type Modifiers
Modify the basic types to change their range:
| Modifier | Meaning | Example | Range Change |
|---|---|---|---|
signed |
Can be positive or negative | signed int |
-2 billion to +2 billion |
unsigned |
Only positive (0 and up) | unsigned int |
0 to 4 billion |
short |
Smaller size | short int |
-32,768 to +32,767 |
long |
Larger size | long int |
Very large numbers |
#include <stdio.h>
int main() {
// Regular int
int regular = 100;
// Unsigned int - only positive, double the positive range
unsigned int positive_only = 4000000000U;
// Short int - smaller range, less memory
short int small_number = 1000;
// Long int - larger range
long int big_number = 9999999999L;
// Print with correct format specifiers
printf("Regular: %d\n", regular);
printf("Unsigned: %u\n", positive_only);
printf("Short: %hd\n", small_number);
printf("Long: %ld\n", big_number);
// Sizeof operator shows actual bytes used
printf("\nMemory sizes:\n");
printf("char: %zu bytes\n", sizeof(char));
printf("int: %zu bytes\n", sizeof(int));
printf("float: %zu bytes\n", sizeof(float));
printf("double: %zu bytes\n", sizeof(double));
return 0;
}
đ Constants in C
Constants are values that cannot be changed after they're set. Use them for values that should stay fixed.
Method 1: const Keyword
#include <stdio.h>
int main() {
// const prevents modification
const double PI = 3.14159;
const int MAX_SIZE = 100;
const char NEWLINE = '\n';
printf("PI = %f\n", PI);
printf("Max size = %d\n", MAX_SIZE);
// PI = 3.14; // â ERROR: Cannot modify const variable!
return 0;
}
Method 2: #define Preprocessor
#include <stdio.h>
// Define constants BEFORE main()
#define PI 3.14159
#define MAX_SIZE 100
#define GREETING "Hello, World!"
#define NEWLINE '\n'
int main() {
// These are replaced by preprocessor before compilation
printf("PI = %f\n", PI);
printf("Max size = %d\n", MAX_SIZE);
printf("%s%c", GREETING, NEWLINE);
return 0;
}
đĄ const vs #define: Which to use?
| Feature | const | #define |
|---|---|---|
| Type safety | â Has a type (compiler checks) | â No type (text replacement) |
| Memory | Uses memory | No memory (replaced at compile time) |
| Scope | Follows scope rules | Global (from #define onwards) |
| Best for | Typed constants, local scope | Configuration values, array sizes |
Recommendation: Prefer const in modern C. Use #define only for conditional compilation.
đ Literals in C
Literals are fixed values written directly in code. They're the actual data you type.
Integer Literals
42- Decimal (base 10)052- Octal (base 8, starts with 0)0x2A- Hexadecimal (base 16, starts with 0x)42U- Unsigned42L- Long
Floating-Point Literals
3.14- Regular decimal3.14f- Float (suffix f)3.14L- Long double2.5e2- Scientific (2.5 à 10² = 250)
Character Literals
'A'- Single character'\n'- Newline'\t'- Tab'\\'- Backslash'\''- Single quote
#include <stdio.h>
int main() {
// Different number representations
int decimal = 42; // Regular
int octal = 052; // Octal: 052 = 42 decimal
int hex = 0x2A; // Hexadecimal: 0x2A = 42 decimal
printf("All represent 42:\n");
printf("Decimal: %d\n", decimal);
printf("Octal 052 = %d\n", octal);
printf("Hex 0x2A = %d\n\n", hex);
// Scientific notation
double large = 2.5e6; // 2.5 Ã 10^6 = 2,500,000
double small = 1.5e-3; // 1.5 Ã 10^-3 = 0.0015
printf("2.5e6 = %f\n", large);
printf("1.5e-3 = %f\n\n", small);
// Characters and their ASCII values
char letter = 'A';
printf("Character: %c\n", letter);
printf("ASCII value: %d\n\n", letter);
// String literal
char greeting[] = "Hello, World!";
printf("String: %s\n", greeting);
return 0;
}
âŠī¸ Escape Sequences
Special characters that start with a backslash (\). They represent non-printable or special characters.
| Sequence | Name | Effect | Example Output |
|---|---|---|---|
\n |
Newline | Move to next line | Line 1 Line 2 |
\t |
Tab | Horizontal spacing | Col1 Col2 |
\\ |
Backslash | Print backslash | C:\Users\Name |
\" |
Double quote | Print " | He said "Hi" |
\' |
Single quote | Print ' | It's ok |
\0 |
Null | String terminator | (invisible) |
#include <stdio.h>
int main() {
// Newline
printf("Line 1\nLine 2\nLine 3\n\n");
// Tab for alignment
printf("Name:\tAlice\n");
printf("Age:\t25\n");
printf("City:\tNYC\n\n");
// Quotes inside string
printf("He said, \"Hello!\"\n");
printf("It's a beautiful day\\n");
// Backslash for paths
printf("File path: C:\\Users\\Alice\\Documents\n");
return 0;
}
đ Complete Example: Student Record
#include <stdio.h>
// Constants
#define SCHOOL_NAME "Tech High"
#define MAX_GRADE 100
int main() {
// Student information using various types
char name[] = "Alice Johnson";
char grade = 'A';
int age = 20;
unsigned int student_id = 2024001U;
float gpa = 3.85f;
double tuition = 12500.50;
// Display information with formatting
printf("ââââââââââââââââââââââââââââââââââ\n");
printf("â STUDENT INFORMATION â\n");
printf("â âââââââââââââââââââââââââââââââââŖ\n");
printf("â School: %-22s â\n", SCHOOL_NAME);
printf("â Name: %-24s â\n", name);
printf("â Age: %-25d â\n", age);
printf("â Student ID: %-18u â\n", student_id);
printf("â Grade: %-23c â\n", grade);
printf("â GPA: %-25.2f â\n", gpa);
printf("â Tuition: $%-21.2lf â\n", tuition);
printf("ââââââââââââââââââââââââââââââââââ\n");
// Memory usage
printf("\nMemory used by variables:\n");
printf("Name: %zu bytes\n", sizeof(name));
printf("Age: %zu bytes\n", sizeof(age));
printf("GPA: %zu bytes\n", sizeof(gpa));
printf("Tuition: %zu bytes\n", sizeof(tuition));
return 0;
}
đ¯ What This Demonstrates
char[]for strings (names)charfor single letter gradesintandunsigned intfor different rangesfloatanddoublefor different precision needs#definefor constant school namesizeof()to check memory usage