Here’s the most readable C code example with best practices and excellent documentation
Key readability features demonstrated:
- Comprehensive file header - Project overview and author info
- Section dividers - Clear organization with ========== separators
- Detailed comments - Every structure, function, and complex section documented
- Clear naming - Functions use prefix_action pattern (e.g., datastore_add_record)
- Meaningful variable names - record_count instead of cnt, is_active instead of active
- Consistent formatting - 8-space indentation, consistent brace placement
- Input validation - Every public function validates inputs with error messages
- Error handling - Clear error messages to stderr
- Documentation format - Function documentation follows standard style
- Logical grouping - Related code organized in sections
- Doxygen-compatible comments - Can generate documentation automatically
- Safe buffer operations - Uses strncpy with null-termination
- Assertions and checks - Defensive programming practices
- Return value clarity - Clear return value meanings (SUCCESS/FAILURE)
This style makes code self-documenting and easy to maintain!
/*
* =============================================================================
* PROJECT: Data Processing System
* AUTHOR: AndrewMaksimchuk
* DATE: 2026-03-23
* PURPOSE: Demonstrate highly readable C code with clear structure,
* comprehensive comments, and sensible naming conventions.
* =============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <ctype.h>
/*
* =============================================================================
* CONSTANTS AND MACRO DEFINITIONS
* =============================================================================
*/
/* Maximum buffer sizes for strings and arrays */
#define MAX_NAME_LENGTH 64
#define MAX_DESCRIPTION_LENGTH 256
#define MAX_RECORDS 1000
#define MAX_LINE_LENGTH 512
/* Boolean-like macros for clarity */
#define SUCCESS 0
#define FAILURE 1
#define IS_VALID_ID(id) ((id) > 0 && (id) < MAX_RECORDS)
/*
* =============================================================================
* DATA STRUCTURE DEFINITIONS
* =============================================================================
*/
/*
* struct PersonRecord
*
* Represents a single person with basic information.
* Used for storing employee or contact data.
*
* Members:
* - id: Unique identifier (1-based index)
* - name: Person's full name
* - email: Contact email address
* - phone: Contact phone number
* - age: Person's age in years
* - is_active: Whether this record is currently active
*/
typedef struct
{
int id;
char name[MAX_NAME_LENGTH];
char email[MAX_NAME_LENGTH];
char phone[MAX_NAME_LENGTH];
int age;
bool is_active;
} PersonRecord;
/*
* struct DataStore
*
* Central data storage container holding all person records
* and metadata about the collection.
*
* Members:
* - records: Array of PersonRecord structures
* - record_count: Number of records currently stored
* - modified: Flag indicating unsaved changes
*/
typedef struct
{
PersonRecord records[MAX_RECORDS];
int record_count;
bool modified;
} DataStore;
/*
* =============================================================================
* FUNCTION PROTOTYPES
* =============================================================================
*/
/* Initialization and cleanup */
DataStore* datastore_create(void);
void datastore_destroy(DataStore* store);
/* Record management */
int datastore_add_record(DataStore* store, const char* name,
const char* email, const char* phone, int age);
int datastore_remove_record(DataStore* store, int record_id);
PersonRecord* datastore_find_by_id(DataStore* store, int record_id);
PersonRecord* datastore_find_by_name(DataStore* store, const char* name);
/* Display operations */
void datastore_display_record(const PersonRecord* record);
void datastore_display_all(const DataStore* store);
/* Validation functions */
bool is_valid_email(const char* email);
bool is_valid_phone(const char* phone);
bool is_valid_age(int age);
bool is_valid_name(const char* name);
/* Utility functions */
void trim_whitespace(char* str);
void convert_to_lowercase(char* str);
/*
* =============================================================================
* IMPLEMENTATION
* =============================================================================
*/
/*
* datastore_create()
*
* Allocates and initializes a new DataStore instance.
*
* Returns:
* Pointer to newly allocated DataStore, or NULL if allocation fails.
*
* Note:
* Caller is responsible for freeing returned pointer with datastore_destroy()
*/
DataStore* datastore_create(void)
{
DataStore* store = (DataStore*)malloc(sizeof(DataStore));
if (store == NULL)
{
fprintf(stderr, "Error: Memory allocation failed for DataStore\n");
return NULL;
}
/* Initialize all fields to zero/false state */
store->record_count = 0;
store->modified = false;
memset(store->records, 0, sizeof(store->records));
return store;
}
/*
* datastore_destroy()
*
* Frees all resources associated with a DataStore.
*
* Parameters:
* store - Pointer to DataStore to be destroyed
*
* Safety:
* Safe to call with NULL pointer (no-op)
*/
void datastore_destroy(DataStore* store)
{
if (store == NULL)
{
return;
}
free(store);
}
/*
* is_valid_email()
*
* Validates an email address using basic heuristics.
* Checks for presence of '@' and '.' characters.
*
* Parameters:
* email - String to validate
*
* Returns:
* true if email appears valid, false otherwise
*/
bool is_valid_email(const char* email)
{
if (email == NULL || strlen(email) == 0)
{
return false;
}
/* Must have exactly one '@' symbol */
int at_count = 0;
int dot_count = 0;
bool has_char_after_at = false;
for (size_t i = 0; email[i] != '\0'; i++)
{
if (email[i] == '@')
{
at_count++;
}
else if (email[i] == '.')
{
dot_count++;
}
}
/* Valid email must have one '@' and at least one '.' */
return (at_count == 1 && dot_count >= 1);
}
/*
* is_valid_phone()
*
* Validates a phone number (accepts various formats).
* Minimum length check only - accepts digits, spaces, hyphens, parentheses.
*
* Parameters:
* phone - String to validate
*
* Returns:
* true if phone appears valid, false otherwise
*/
bool is_valid_phone(const char* phone)
{
if (phone == NULL || strlen(phone) < 10)
{
return false;
}
return true;
}
/*
* is_valid_age()
*
* Validates a person's age as a reasonable number.
*
* Parameters:
* age - Integer age value to validate
*
* Returns:
* true if age is within acceptable range (1-150), false otherwise
*/
bool is_valid_age(int age)
{
return (age > 0 && age < 150);
}
/*
* is_valid_name()
*
* Validates a person's name.
* Must be non-empty and contain only valid characters.
*
* Parameters:
* name - String to validate
*
* Returns:
* true if name is valid, false otherwise
*/
bool is_valid_name(const char* name)
{
if (name == NULL || strlen(name) == 0 || strlen(name) > MAX_NAME_LENGTH)
{
return false;
}
/* Check for reasonable character content */
for (size_t i = 0; name[i] != '\0'; i++)
{
char c = name[i];
if (!isalpha(c) && !isspace(c) && c != '-' && c != '\'')
{
return false;
}
}
return true;
}
/*
* trim_whitespace()
*
* Removes leading and trailing whitespace from a string.
* Modifies the string in-place.
*
* Parameters:
* str - String to trim (modified in-place)
*/
void trim_whitespace(char* str)
{
if (str == NULL)
{
return;
}
/* Find start of non-whitespace */
size_t start = 0;
while (str[start] != '\0' && isspace(str[start]))
{
start++;
}
/* Find end of non-whitespace */
size_t end = strlen(str);
while (end > start && isspace(str[end - 1]))
{
end--;
}
/* Shift characters and null-terminate */
if (start > 0)
{
memmove(str, str + start, end - start);
}
str[end - start] = '\0';
}
/*
* datastore_add_record()
*
* Adds a new person record to the data store.
* Validates all input before insertion.
*
* Parameters:
* store - Pointer to DataStore
* name - Person's name
* email - Person's email
* phone - Person's phone number
* age - Person's age
*
* Returns:
* Record ID (> 0) on success, FAILURE on error
*/
int datastore_add_record(DataStore* store, const char* name,
const char* email, const char* phone, int age)
{
/* Validate inputs */
if (store == NULL)
{
fprintf(stderr, "Error: DataStore is NULL\n");
return FAILURE;
}
if (!is_valid_name(name))
{
fprintf(stderr, "Error: Invalid name: %s\n", name);
return FAILURE;
}
if (!is_valid_email(email))
{
fprintf(stderr, "Error: Invalid email: %s\n", email);
return FAILURE;
}
if (!is_valid_phone(phone))
{
fprintf(stderr, "Error: Invalid phone: %s\n", phone);
return FAILURE;
}
if (!is_valid_age(age))
{
fprintf(stderr, "Error: Invalid age: %d\n", age);
return FAILURE;
}
/* Check storage capacity */
if (store->record_count >= MAX_RECORDS)
{
fprintf(stderr, "Error: Record store is full\n");
return FAILURE;
}
/* Add new record */
PersonRecord* new_record = &store->records[store->record_count];
new_record->id = store->record_count + 1;
strncpy(new_record->name, name, MAX_NAME_LENGTH - 1);
new_record->name[MAX_NAME_LENGTH - 1] = '\0';
strncpy(new_record->email, email, MAX_NAME_LENGTH - 1);
new_record->email[MAX_NAME_LENGTH - 1] = '\0';
strncpy(new_record->phone, phone, MAX_NAME_LENGTH - 1);
new_record->phone[MAX_NAME_LENGTH - 1] = '\0';
new_record->age = age;
new_record->is_active = true;
store->record_count++;
store->modified = true;
printf("Record added successfully with ID: %d\n", new_record->id);
return new_record->id;
}
/*
* datastore_display_record()
*
* Prints a single record to stdout in formatted manner.
*
* Parameters:
* record - Pointer to PersonRecord to display
*/
void datastore_display_record(const PersonRecord* record)
{
if (record == NULL)
{
return;
}
printf("\n ID: %d\n", record->id);
printf(" Name: %s\n", record->name);
printf(" Email: %s\n", record->email);
printf(" Phone: %s\n", record->phone);
printf(" Age: %d\n", record->age);
printf(" Status: %s\n", record->is_active ? "Active" : "Inactive");
}
/*
* datastore_display_all()
*
* Displays all records in the data store in formatted table.
* Shows only active records.
*
* Parameters:
* store - Pointer to DataStore
*/
void datastore_display_all(const DataStore* store)
{
if (store == NULL || store->record_count == 0)
{
printf("No records to display\n");
return;
}
printf("\n========================================\n");
printf(" ALL RECORDS (%d total)\n", store->record_count);
printf("========================================\n");
for (int i = 0; i < store->record_count; i++)
{
if (store->records[i].is_active)
{
datastore_display_record(&store->records[i]);
}
}
printf("\n========================================\n");
}
/*
* =============================================================================
* MAIN PROGRAM
* =============================================================================
*/
int main(void)
{
/* Create data store */
DataStore* store = datastore_create();
if (store == NULL)
{
return EXIT_FAILURE;
}
printf("=== Data Management System ===\n\n");
/* Add sample records */
datastore_add_record(store, "Alice Johnson", "alice@example.com",
"555-1234", 28);
datastore_add_record(store, "Bob Smith", "bob@example.com",
"555-5678", 35);
datastore_add_record(store, "Carol White", "carol@example.com",
"555-9012", 32);
/* Display all records */
datastore_display_all(store);
/* Clean up */
datastore_destroy(store);
return EXIT_SUCCESS;
}