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 : +voidType Modifiers:
mindmap
root((Type Modifiers))
signed
unsigned
short
long
long longExample with unsigned:
unsigned int population = 30000000; // Nepal's population
Variables: Declaration and Initialization
Variable Declaration Rules
- Must declare before use
- Name must start with letter/underscore
- Case-sensitive (
age≠Age) - 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
State 1: Uninitialized
State 2: Initialized to 0 (global/static)
State 3: Initialized to garbage (local)
State 4: Explicitly initialized
Example with Khalti transaction:
float transaction_amount = 5000.50; // Initialized
int transaction_count; // Uninitialized (risky!)
Constants in C
Two Ways to Define Constants
- Preprocessor Macros (
#define) constQualifier
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
Four Storage Classes in C
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
State 1: Stack (auto variables)
State 2: Static Memory (globals, static)
State 3: Heap (dynamic memory)
Best Practices:
- Always initialize variables
- Use
constfor values that shouldn't change - Prefer
staticfor persistent local state - Avoid
register(modern compilers optimize better) - Use meaningful variable names (e.g.,
customer_balanceinstead ofcb)
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
eSewa Payment System
- Uses
unsigned intfor transaction IDs to ensure positive values - Employs
constfor fixed fees like service charges - Declares
staticvariables to maintain user session data across function calls
- Uses
Khalti Wallet
- Implements
floatfor currency values to handle decimal rupees - Uses arrays to store transaction history
- Applies
externfor shared configuration across modules
- Implements
NTC Billing Software
- Utilizes
doublefor precise energy consumption calculations - Maintains customer data using structures
- Employs constants for fixed tariff rates
- Utilizes
Pathao Driver App
- Uses
chararrays to store driver names and vehicle types - Implements
staticcounters for trip statistics - Applies type modifiers like
unsigned longfor large distance values
- Uses
Exam Tip
Common Exam Patterns for This Unit:
Declaration Questions (30%)
- Write declarations for given scenarios
- Example: "Declare a variable to store Nepal's population"
Type Selection (25%)
- Choose appropriate data types for given requirements
- Example: "Which type would you use to store a mobile phone price?"
Constant Usage (20%)
- Identify where to use
#definevsconst - Example: "Convert this magic number to a named constant"
- Identify where to use
Storage Class Application (15%)
- Determine appropriate storage class for given scenarios
- Example: "Why would you use
staticfor this counter variable?"
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
#defineandconstversions when asked - In traces, show all relevant variables at each step
Sample Exam Question Solution:
Question: Declare variables to store:
- A customer's name (max 50 characters)
- The total bill amount
- 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:
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…