Variables, Data Types & Constants
Duration: 50 min
Variables are containers for storing data values. C is a statically-typed language, meaning you must declare the type of each variable before using it. Understanding data types is fundamental to writing efficient C programs.
Basic Data Types
C provides several fundamental data types:
#include <stdio.h>
int main() {
int age = 25; // Integer: -2147483648 to 2147483647
float height = 5.9; // Floating-point: ~6-7 decimal places
double weight = 72.5; // Double precision: ~15 decimal places
char grade = 'A'; // Single character
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Weight: %.1f\n", weight);
printf("Grade: %c\n", grade);
return 0;
}Variable Declaration & Initialization
#include <stdio.h>
int main() {
// Declaration without initialization
int x;
// Declaration with initialization
int y = 10;
// Multiple declarations
int a = 5, b = 10, c = 15;
// Using variables
int sum = a + b + c;
printf("Sum: %d\n", sum);
return 0;
}The sizeof Operator
#include <stdio.h>
int main() {
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of float: %lu bytes\n", sizeof(float));
printf("Size of double: %lu bytes\n", sizeof(double));
printf("Size of char: %lu bytes\n", sizeof(char));
// Typical output on 64-bit systems:
// Size of int: 4 bytes
// Size of float: 4 bytes
// Size of double: 8 bytes
// Size of char: 1 byte
return 0;
}Constants
Constants are variables whose values cannot be changed after initialization:
#include <stdio.h>
int main() {
// Using const keyword
const int MAX_USERS = 100;
const float PI = 3.14159;
// This would cause a compilation error:
// MAX_USERS = 200; // Error: assignment of read-only variable
printf("Max users: %d\n", MAX_USERS);
printf("Pi: %.5f\n", PI);
return 0;
}Naming Conventions & Best Practices
#include <stdio.h>
int main() {
// Good variable names (descriptive, lowercase with underscores)
int student_age = 20;
float average_score = 85.5;
char first_initial = 'J';
// Constants in UPPERCASE
const int MAX_ATTEMPTS = 3;
const float GRAVITY = 9.8;
// Avoid single letters except for loop counters
// int x = 10; // Not descriptive
// int num_items = 10; // Better
return 0;
}Quiz 1: Data Types
❓ Which data type should you use for storing a person's age?
Quiz 2: sizeof Operator
❓ What does `sizeof(int)` typically return on a 64-bit system?
Quiz 3: Constants
❓ What happens if you try to modify a const variable?
Quiz 4: Variable Initialization
❓ What is the value of an uninitialized int variable?
Quiz 5: Float vs Double
❓ What is the main difference between float and double?