The Ultimate Guide to C Language Code Standards: Make Your Colleagues Go Crazy for Your Code!

Introduction: Have you ever faced such an awkward situation? During a code review, a colleague frowns and says, “This code… works, I guess?” Or when taking over someone else’s project, you see a pile of code that looks like a foreign language and want to explode? Today, I will share a set of ultimate secrets to elevate your C language code from “it works” to “elegant”!

šŸ’” Why Are Code Standards So Important?

Real Case Sharing

When you intern at a big company, you encounter a project that drives you crazy:

  • Variable names are all in pinyin:<span>int shuliang = 0;</span>
  • Functions are 200 lines long, with 8 layers of nested if-else
  • No comments, even the author can’t understand it

The result? The maintenance cost of this project is three times that of a normal project!

Data Speaks:

  • The bug rate of elegant code is 40% lower than that of chaotic code
  • Code review time is reduced by 60%
  • Newcomers’ onboarding time is shortened by 70%

The Ultimate Guide to C Language Code Standards: Make Your Colleagues Go Crazy for Your Code!

Code Quality Comparison

šŸŽÆ Chapter 1: Naming Conventions – Let the Code Speak for Itself

1.1 The Golden Rule of Variable Naming

āŒ Bad Example:

1int a, b, c;
2char str[100];
3float f1, f2;

āœ… Good Example:

1int student_count;
2int max_buffer_size;
3char user_name[MAX_NAME_LENGTH];
4float temperature_celsius;
5float humidity_percentage;

1.2 The Art of Function Naming

Core Principle: Verb + Noun, Clearly Express Intent

1// āŒ Poor Naming
2int calc(int x, int y);
3void proc();
4
5// āœ… Elegant Naming
6int calculate_monthly_salary(int base_salary, int bonus);
7void process_user_input();
8bool is_valid_email(const char* email);

1.3 Constants and Macro Definition Standards

 1// āœ… All uppercase, separated by underscores
 2#define MAX_STUDENTS 100
 3#define PI 3.14159265359
 4#define ERROR_CODE_INVALID_INPUT -1
 5
 6// āœ… Enum type naming
 7typedef enum {
 8    STATUS_SUCCESS = 0,
 9    STATUS_ERROR = -1,
10    STATUS_PENDING = 1
11} operation_status_t;

The Ultimate Guide to C Language Code Standards: Make Your Colleagues Go Crazy for Your Code!

Naming Convention Guide

šŸ—ļø Chapter 2: Code Structure – Building a Clear Logical Framework

2.1 SOLID Principles of Function Design

Single Responsibility Principle in Action:

 1// āŒ A function doing too many things
 2void process_student_data(student_t* students, int count) {
 3    // Validate data
 4    for(int i = 0; i < count; i++) {
 5        if(students[i].age < 0 || students[i].age > 150) {
 6            printf("Invalid age\n");
 7            return;
 8        }
 9    }
10
11    // Calculate average score
12    float total = 0;
13    for(int i = 0; i < count; i++) {
14        total += students[i].score;
15    }
16    float average = total / count;
17
18    // Print result
19    printf("Average score: %.2f\n", average);
20}
21
22// āœ… Responsibilities separated, elegant and clear
23bool validate_student_data(const student_t* students, int count) {
24    for(int i = 0; i < count; i++) {
25        if(students[i].age < 0 || students[i].age > 150) {
26            return false;
27        }
28    }
29    return true;
30}
31
32float calculate_average_score(const student_t* students, int count) {
33    if(count == 0) return 0.0f;
34
35    float total = 0;
36    for(int i = 0; i < count; i++) {
37        total += students[i].score;
38    }
39    return total / count;
40}
41
42void print_statistics(float average_score) {
43    printf("Average score: %.2f\n", average_score);
44}

The Ultimate Guide to C Language Code Standards: Make Your Colleagues Go Crazy for Your Code!

Function Design Principles

2.2 Elegant Error Handling

 1// āœ… Unified error handling pattern
 2typedef enum {
 3    RESULT_SUCCESS = 0,
 4    RESULT_NULL_POINTER = -1,
 5    RESULT_INVALID_PARAMETER = -2,
 6    RESULT_MEMORY_ERROR = -3
 7} result_code_t;
 8
 9result_code_t safe_string_copy(char* dest, const char* src, size_t dest_size) {
10    if(dest == NULL || src == NULL) {
11        return RESULT_NULL_POINTER;
12    }
13
14    if(dest_size == 0) {
15        return RESULT_INVALID_PARAMETER;
16    }
17
18    size_t src_len = strlen(src);
19    if(src_len >= dest_size) {
20        return RESULT_INVALID_PARAMETER;
21    }
22
23    strcpy(dest, src);
24    return RESULT_SUCCESS;
25}

šŸ“ Chapter 3: The Art of Commenting – Let the Code Tell a Story

3.1 The Golden Ratio of Comments

Good comments explain “why” rather than “what”

 1// āŒ Useless comment
 2int i = 0; // Initialize i to 0
 3
 4// āœ… Valuable comment
 5/**
 6 * Use binary search algorithm to improve search efficiency for large datasets
 7 * Time complexity: O(log n)
 8 * Preconditions: Array must be sorted
 9 */
10int binary_search(const int* arr, int size, int target) {
11    int left = 0;
12    int right = size - 1;
13
14    while(left <= right) {
15        // Safe calculation to prevent integer overflow
16        int mid = left + (right - left) / 2;
17
18        if(arr[mid] == target) {
19            return mid;
20        } else if(arr[mid] < target) {
21            left = mid + 1;
22        } else {
23            right = mid - 1;
24        }
25    }
26
27    return -1; // Target value not found
28}

3.2 Documentation Comment Standards

 1/**
 2 * @brief Calculate the greatest common divisor of two integers
 3 * @param a The first integer
 4 * @param b The second integer
 5 * @return The greatest common divisor, returns 0 if input is invalid
 6 * @note Implemented using Euclidean algorithm
 7 * @example
 8 *   int result = gcd(48, 18); // Returns 6
 9 */
10int gcd(int a, int b) {
11    if(a < 0) a = -a;
12    if(b < 0) b = -b;
13
14    if(a == 0 || b == 0) {
15        return 0;
16    }
17
18    while(b != 0) {
19        int temp = b;
20        b = a % b;
21        a = temp;
22    }
23
24    return a;
25}

šŸŽØ Chapter 4: Code Formatting – The Power of Visual Aesthetics

4.1 The Art of Indentation and Spacing

 1// āœ… Clear indentation and spacing usage
 2if (condition1 && condition2) {
 3    for (int i = 0; i < max_count; i++) {
 4        if (array[i] > threshold) {
 5            result = process_item(array[i]);
 6
 7            if (result == SUCCESS) {
 8                success_count++;
 9            } else {
10                log_error("Processing failed for item %d", i);
11            }
12        }
13    }
14}

4.2 Code Block Organization Standards

 1// āœ… Logical grouping for improved readability
 2int main() {
 3    // 1. Initialization phase
 4    int result = 0;
 5    char buffer[BUFFER_SIZE];
 6    student_t* students = NULL;
 7
 8    // 2. Memory allocation
 9    students = malloc(sizeof(student_t) * MAX_STUDENTS);
10    if (students == NULL) {
11        fprintf(stderr, "Memory allocation failed\n");
12        return EXIT_FAILURE;
13    }
14
15    // 3. Data processing
16    result = load_student_data(students, MAX_STUDENTS);
17    if (result != SUCCESS) {
18        goto cleanup;
19    }
20
21    result = process_student_data(students, MAX_STUDENTS);
22    if (result != SUCCESS) {
23        goto cleanup;
24    }
25
26    // 4. Result output
27    print_student_statistics(students, MAX_STUDENTS);
28
29cleanup:
30    // 5. Resource cleanup
31    if (students != NULL) {
32        free(students);
33        students = NULL;
34    }
35
36    return result == SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
37}

šŸ›”ļø Chapter 5: Secure Programming – Defensive Programming Mindset

5.1 The Importance of Input Validation

 1// āœ… Comprehensive input validation
 2result_code_t safe_array_access(const int* array, size_t array_size, size_t index, int* value) {
 3    // Parameter validity check
 4    if (array == NULL) {
 5        return RESULT_NULL_POINTER;
 6    }
 7
 8    if (value == NULL) {
 9        return RESULT_NULL_POINTER;
10    }
11
12    if (array_size == 0) {
13        return RESULT_INVALID_PARAMETER;
14    }
15
16    // Boundary check
17    if (index >= array_size) {
18        return RESULT_INDEX_OUT_OF_BOUNDS;
19    }
20
21    *value = array[index];
22    return RESULT_SUCCESS;
23}

5.2 Best Practices for Memory Management

 1// āœ… Safe memory management pattern
 2typedef struct {
 3    char* data;
 4    size_t size;
 5    size_t capacity;
 6} dynamic_buffer_t;
 7
 8result_code_t buffer_create(dynamic_buffer_t** buffer, size_t initial_capacity) {
 9    if (buffer == NULL || initial_capacity == 0) {
10        return RESULT_INVALID_PARAMETER;
11    }
12
13    *buffer = malloc(sizeof(dynamic_buffer_t));
14    if (*buffer == NULL) {
15        return RESULT_MEMORY_ERROR;
16    }
17
18    (*buffer)->data = malloc(initial_capacity);
19    if ((*buffer)->data == NULL) {
20        free(*buffer);
21        *buffer = NULL;
22        return RESULT_MEMORY_ERROR;
23    }
24
25    (*buffer)->size = 0;
26    (*buffer)->capacity = initial_capacity;
27
28    return RESULT_SUCCESS;
29}
30
31void buffer_destroy(dynamic_buffer_t** buffer) {
32    if (buffer != NULL && *buffer != NULL) {
33        if ((*buffer)->data != NULL) {
34            free((*buffer)->data);
35            (*buffer)->data = NULL;
36        }
37
38        free(*buffer);
39        *buffer = NULL;
40    }
41}

šŸš€ Chapter 6: Performance Optimization – Let the Code Fly

6.1 Algorithm Complexity Optimization

 1// āŒ Inefficient implementation O(n²)
 2bool has_duplicate_slow(const int* array, size_t size) {
 3    for (size_t i = 0; i < size; i++) {
 4        for (size_t j = i + 1; j < size; j++) {
 5            if (array[i] == array[j]) {
 6                return true;
 7            }
 8        }
 9    }
10    return false;
11}
12
13// āœ… Optimized implementation O(n log n)
14bool has_duplicate_fast(int* array, size_t size) {
15    if (size <= 1) {
16        return false;
17    }
18
19    // Sort first
20    qsort(array, size, sizeof(int), compare_int);
21
22    // Check adjacent elements
23    for (size_t i = 1; i < size; i++) {
24        if (array[i] == array[i-1]) {
25            return true;
26        }
27    }
28
29    return false;
30}

šŸŽÆ Chapter 7: Team Collaboration – Unifying Code Standards

7.1 Project Structure Standards

1project/
2ā”œā”€ā”€ src/           # Source code
3│   ā”œā”€ā”€ core/      # Core functionality modules
4│   ā”œā”€ā”€ utils/     # Utility functions
5│   └── tests/     # Unit tests
6ā”œā”€ā”€ include/       # Header files
7ā”œā”€ā”€ docs/          # Documentation
8ā”œā”€ā”€ build/         # Build output
9└── README.md      # Project description

7.2 Header File Organization Standards

 1// āœ… Standard header file structure
 2#ifndef STUDENT_MANAGER_H
 3#define STUDENT_MANAGER_H
 4
 5// 1. System header files
 6#include <stdio.h>
 7#include <stdlib.h>
 8#include <string.h>
 9
10// 2. Third-party library header files
11#include <sqlite3.h>
12
13// 3. Internal project header files
14#include "common_types.h"
15#include "error_codes.h"
16
17// 4. Macro definitions
18#define MAX_STUDENT_NAME_LENGTH 64
19#define MAX_STUDENTS_PER_CLASS 50
20
21// 5. Type definitions
22typedef struct {
23    char name[MAX_STUDENT_NAME_LENGTH];
24    int age;
25    float score;
26    int student_id;
27} student_t;
28
29// 6. Function declarations
30result_code_t student_create(student_t** student, const char* name, int age, float score);
31void student_destroy(student_t** student);
32result_code_t student_validate(const student_t* student);
33
34#endif // STUDENT_MANAGER_H

šŸ’Ž Chapter 8: Code Review Checklist – Your Self-Check Tool

8.1 Pre-Submission Self-Check Checklist

Naming Convention Check:

  • xVariable names clearly express meaning

    xFunction names use verb + noun format

    xConstants use all uppercase naming

    xAvoid using abbreviations and pinyin

Code Structure Check:

  • xFunction length does not exceed 50 lines

    xNested levels do not exceed 4 layers

    xEach function does one thing

    xComplete error handling

Security Check:

  • xAll pointers checked for NULL before use

    xArray access performs boundary checks

    xCheck memory allocation success after allocation

    xResources released in a timely manner after use

šŸ† Chapter 9: Practical Case Studies – Before and After Code Refactoring Comparison

9.1 Refactoring Practice: Student Management System

Chaotic code before refactoring:

 1// āŒ Chaotic original code
 2void func(char *s[], int n) {
 3    int i,j;
 4    for(i=0;i<n;i++) {
 5        for(j=0;j<strlen(s[i]);j++) {
 6            if(s[i][j]>='a'&&s[i][j]<='z') s[i][j]=s[i][j]-32;
 7        }
 8        printf("%s\n",s[i]);
 9    }
10}

Elegant code after refactoring:

 1// āœ… Elegant code after refactoring
 2/**
 3 * @brief Convert all strings in an array to uppercase and print
 4 * @param strings Array of strings
 5 * @param count Number of strings
 6 * @return Operation result code
 7 */
 8result_code_t convert_and_print_uppercase(char* strings[], size_t count) {
 9    if (strings == NULL) {
10        return RESULT_NULL_POINTER;
11    }
12
13    for (size_t i = 0; i < count; i++) {
14        if (strings[i] == NULL) {
15            fprintf(stderr, "Warning: NULL string at index %zu\n", i);
16            continue;
17        }
18
19        result_code_t result = convert_to_uppercase(strings[i]);
20        if (result != RESULT_SUCCESS) {
21            return result;
22        }
23
24        printf("%s\n", strings[i]);
25    }
26
27    return RESULT_SUCCESS;
28}
29
30/**
31 * @brief Convert a string to uppercase
32 * @param str The string to convert
33 * @return Operation result code
34 */
35static result_code_t convert_to_uppercase(char* str) {
36    if (str == NULL) {
37        return RESULT_NULL_POINTER;
38    }
39
40    for (size_t i = 0; str[i] != '\0'; i++) {
41        if (str[i] >= 'a' && str[i] <= 'z') {
42            str[i] = str[i] - ('a' - 'A');
43        }
44    }
45
46    return RESULT_SUCCESS;
47}

The Ultimate Guide to C Language Code Standards: Make Your Colleagues Go Crazy for Your Code!

Code Refactoring Comparison

Core Points Review:

  1. Naming is Documentation – Good naming lets the code speak for itself
  2. Single Responsibility for Functions – A function should do one thing and do it well
  3. Defensive Programming – Never trust input, always check boundaries
  4. Comments Explain Intent – Explain why you did it this way, not what you did
  5. Unified Team Standards – Consistency in code style is more important than personal preference

Immediate Action Plan:

Week 1: Refactor your 3 most frequently used functionsWeek 2: Create a code standard document for your projectWeek 3: Promote these best practices within your teamWeek 4: Establish a code review process

The Ultimate Guide to C Language Code Standards: Make Your Colleagues Go Crazy for Your Code!

Code Review Checklist

šŸ”„ Bonus: Quick Reference for Major Company Code Standards

Standard Item Google Standard Huawei Standard Alibaba Standard
Indentation 2 spaces 4 spaces 4 spaces
Line Length 80 characters 120 characters 120 characters
Naming Style snake_case snake_case camelCase
Comment Style /* */ /** */ /* */

Your code is your business card!If this was helpful to you, don’t forget to like, bookmark, and share!

Leave a Comment