IT232 C Programming

C ProgrammingUnit 210 min read

Data Types, Variables, Constants & Storage Classes in C

Unit 2 of C Programming covers fundamental building blocks: fundamental and derived data types, variable declaration rules, constant usage, and storage class specifiers with practical examples and real-world applications in Nepalese software systems.

TAKEAWAYS:

  • C has five fundamental data types (int, float, char, double, void) and derived types (arrays, pointers, structures) that determine how data is stored and processed
  • Variables must be declared with type before use and follow strict naming rules (alphanumeric + underscore, no keywords)
  • Constants (#define, const) ensure immutable values critical for security and program reliability
  • Storage classes (auto, register, static, extern) control variable lifetime and scope
  • Type modifiers (signed, unsigned, short, long) extend data range and precision
  • Memory allocation follows strict rules: stack for local variables, static for globals, heap for dynamic memory

Core Concepts: Data Types in C

1. Fundamental Data Types

C provides five primary data types that form the foundation of all other types:

classDiagram
    class FundamentalTypes {
        +int: 2/4 bytes, -32768 to 32767 (short) / -2B to 2B (int)
        +float: 4 bytes, ~6 decimal digits precision
        +double: 8 bytes, ~15 decimal digits precision
        +char: 1 byte, -128 to 127 (signed) / 0 to 255 (unsigned)
        +void: No value, used for functions returning nothing
    }

Key Characteristics:

Type Size (bytes) Typical Range Usage Example
int 2 or 4 -32768 to 32767 (short) Counter variables
float 4 ±3.4e-38 to ±3.4e+38 Scientific calculations
double 8 ±1.7e-308 to ±1.7e+308 High-precision financial data
char 1 -128 to 127 (signed) Single characters
void 0 N/A Function return type

Real-world example:

// Ncell billing system uses float for call duration
float call_duration = 3.75;  // 3 minutes 45 seconds

2. Derived Data Types

Built from fundamental types using type modifiers and qualifiers:

classDiagram
    class DerivedTypes {
        +Arrays: Fixed-size collections
        +Pointers: Memory address references
        +Functions: Code blocks with parameters
        +Structures: Custom composite types
    }
    DerivedTypes --> FundamentalTypes : "Built from fundamental types"
    FundamentalTypes ..> DerivedTypes : "Includes"
    FundamentalTypes : +int
    FundamentalTypes : +float
    FundamentalTypes : +double
    FundamentalTypes : +char
    FundamentalTypes : +void

Type Modifiers:

mindmap
  root((Type Modifiers))
    signed
    unsigned
    short
    long
    long long

Example with unsigned:

unsigned int population = 30000000;  // Nepal's population

Variables: Declaration and Initialization

Variable Declaration Rules

  1. Must declare before use
  2. Name must start with letter/underscore
  3. Case-sensitive (age ≠ Age)
  4. Cannot be C keywords (int, if, etc.)

Example:

int age = 25;          // Valid
int 2age = 25;        // Invalid (starts with number)
int my-age = 25;      // Invalid (contains hyphen)

Variable Initialization

uninitialized0initialized (static)1initialized (dynamic)2
Variable initialization states (static vs. dynamic)
State 1: Uninitialized
State 2: Initialized to 0 (global/static)
State 3: Initialized to garbage (local)
State 4: Explicitly initialized
012345678910Uninitialized (garbage)Initialized (0)Initialized (value)
Variable initialization states (0 vs. garbage vs. explicit)

Example with Khalti transaction:

float transaction_amount = 5000.50;  // Initialized
int transaction_count;               // Uninitialized (risky!)

Constants in C

Two Ways to Define Constants

  1. Preprocessor Macros (#define)
  2. const Qualifier
classDiagram
    class ConstantTypes {
        +#define PI 3.14159
        +const float gravity = 9.81;
    }

Example with NTC electricity rates:

#define UNIT_RATE 3.50  // Per unit cost
const float SERVICE_CHARGE = 150.00;  // Fixed monthly charge

Key Differences:

Feature #define const
Scope File-level Block-level
Type Safety No Yes
Memory Allocation No (text substitution) Yes (memory allocated)

Storage Classes

auto (local)static (local)register (local)extern (global)Global Scope
Storage class scope hierarchy

Four Storage Classes in C

auto (40%)static (30%)register (10%)extern (20%)
Storage class usage distribution (approximate)

Characteristics:

Class Scope Lifetime Memory Location Typical Use Case
auto Block Block duration Stack Local variables
static File/Block Program duration Static memory Persistent local variables
register Block Block duration CPU register Performance-critical variables
extern File/Block Program duration Static memory Global variable declaration

Example with Daraz order processing:

static int total_orders = 0;  // Persists across function calls

Practical Example: Bank Loan Calculator

flowchart TD
    A["Start"] --> B["Input Principal (P)"]
    B --> C["Input Rate (R, %)"]
    C --> D["Input Time (T, years)"]
    D --> E{"Calculate Simple Interest?"}
    E -->|"Yes"| F["I = (P * R * T) / 100"]
    E -->|"No"| G["Exit"]
    F --> H["Output Result: I"]

Code Implementation:

#include <stdio.h>

int main() {
    float principal, rate, time;
    float simple_interest;

    printf("Enter principal amount: ");
    scanf("%f", &principal);

    printf("Enter annual interest rate (%%): ");
    scanf("%f", &rate);

    printf("Enter time in years: ");
    scanf("%f", &time);

    simple_interest = (principal * rate * time) / 100;

    printf("Simple Interest: %.2f\n", simple_interest);
    return 0;
}

Execution Trace:

Step Variable Value
1 principal 500000.00
2 rate 8.5
3 time 5.0
4 simple_interest 21250.00

Real-world application: This exact logic is used by Nepal's commercial banks (NMB, Standard Chartered, Global IME) for calculating loan interest when customers apply for home loans or vehicle financing.


Common Pitfalls and Best Practices

10002001300234
Memory allocation: Stack vs. heap (example)
State 1: Stack (auto variables)
State 2: Static Memory (globals, static)
State 3: Heap (dynamic memory)

Best Practices:

  1. Always initialize variables
  2. Use const for values that shouldn't change
  3. Prefer static for persistent local state
  4. Avoid register (modern compilers optimize better)
  5. Use meaningful variable names (e.g., customer_balance instead of cb)

Common Mistakes:

int count;          // Uninitialized (dangerous!)
#define SIZE 100    // No type safety
register int x = 1000000;  // May not fit in register

In the Real World

  1. eSewa Payment System

    • Uses unsigned int for transaction IDs to ensure positive values
    • Employs const for fixed fees like service charges
    • Declares static variables to maintain user session data across function calls
  2. Khalti Wallet

    • Implements float for currency values to handle decimal rupees
    • Uses arrays to store transaction history
    • Applies extern for shared configuration across modules
  3. NTC Billing Software

    • Utilizes double for precise energy consumption calculations
    • Maintains customer data using structures
    • Employs constants for fixed tariff rates
  4. Pathao Driver App

    • Uses char arrays to store driver names and vehicle types
    • Implements static counters for trip statistics
    • Applies type modifiers like unsigned long for large distance values

Exam Tip

Common Exam Patterns for This Unit:

  1. Declaration Questions (30%)

    • Write declarations for given scenarios
    • Example: "Declare a variable to store Nepal's population"
  2. Type Selection (25%)

    • Choose appropriate data types for given requirements
    • Example: "Which type would you use to store a mobile phone price?"
  3. Constant Usage (20%)

    • Identify where to use #define vs const
    • Example: "Convert this magic number to a named constant"
  4. Storage Class Application (15%)

    • Determine appropriate storage class for given scenarios
    • Example: "Why would you use static for this counter variable?"
  5. Error Identification (10%)

    • Spot declaration errors in given code snippets

High-Scoring Strategies:

  • Always show complete variable declarations with types
  • Include units in comments for real-world examples (e.g., "Rs.")
  • Use Nepalese context in examples (rupees, population, etc.)
  • For constants, show both #define and const versions when asked
  • In traces, show all relevant variables at each step

Sample Exam Question Solution:

Question: Declare variables to store:

  1. A customer's name (max 50 characters)
  2. The total bill amount
  3. A flag indicating if payment is complete

Solution:

char customer_name[51];  // 50 chars + null terminator
float total_bill = 0.0;  // Initialized to zero
const int MAX_NAME_LENGTH = 50;
bool payment_complete = false;

Visualization of Variable States:

500false1
Variable states: const int MAX_NAME_LENGTH = 50; bool payment_complete = false;
State 1: customer_name (uninitialized array)
State 2: total_bill (initialized to 0.0)
State 3: payment_complete (initialized to false)

Based on the TU BITM syllabus for C Programming (IT232), unit 2.

Discussion

Loading…