C Fundamentals

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

Syntax
data_type variable_name;              // Declaration only
data_type variable_name = value;    // Declaration + Initialization
variable_demo.c
#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

  1. int age; - Reserves memory for a whole number, calls it "age"
  2. age = 25; - Puts the value 25 into that memory location
  3. printf("%d", age); - Reads the value from memory and prints it

Rules for Variable Names

✅ Valid Names

  • age, salary, count2
  • _total, student_name
  • totalAmount (camelCase)

❌ Invalid Names

  • 2count - Cannot start with number
  • total amount - No spaces allowed
  • float - 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 range
  • double: 8 bytes = More decimal places than float

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
type_modifiers.c
#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

const_example.c
#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

define_example.c
#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 - Unsigned
  • 42L - Long

Floating-Point Literals

  • 3.14 - Regular decimal
  • 3.14f - Float (suffix f)
  • 3.14L - Long double
  • 2.5e2 - Scientific (2.5 × 10² = 250)

Character Literals

  • 'A' - Single character
  • '\n' - Newline
  • '\t' - Tab
  • '\\' - Backslash
  • '\'' - Single quote
literals_demo.c
#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)
escape_demo.c
#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

student_record.c
#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)
  • char for single letter grades
  • int and unsigned int for different ranges
  • float and double for different precision needs
  • #define for constant school name
  • sizeof() to check memory usage