Skip to content
Rajdeep

Naming in C

Published on - Reading time

Naming is Hard

One wise man once said (did he?):

There are only two hard things in Programming: Naming Variables and Cache Invalidation.

We’ll discuss the latter later.
Naming variables is extremely tough. And functions? You’re in a cult now.

How I do

Functions

First of all, the devil’s sword, functions. For them, I use PascalCase:

pascalcased_fn.c
int Add(int left, int right) {
return left + right;
}
int Factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * Factorial(n - 1);
}
int Strlen(char *str) {
const int MAX = 1024*1024*1024;
int result = 0;
for (int i = 0; str[i] != NULL && i <= MAX; i++) {
result++;
}
return result;
}

The only exception to this, is the main function. And ofc, existing Standard Functions are also exempt.

Structures

So, here comes structs, for which, I use PascalCase:

pascalcased_struct.c
struct Person {
char *name;
int age;
};
struct Point {
int x;
int y;
};
typedef struct {
int data;
struct Node *next;
} Node;

Then, use them as such in functions:

using_structs_in_fn.c
#include <stdlib.h>
#include <stdio.h>
struct Node* CreateNode(int data) {
struct Node *new_node = (Node *)malloc(sizeof(Node));
if (!new_node) {
printf("Memory Allocation failed!\n");
exit(1);
}
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void PrintNode(struct Node *head) {
struct Node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
// Creating Nodes
struct Node *head = CreateNode(1);
head->next = CreateNode(2);
head->next->next = CreateNode(3);
// Print the Node
PrintNode(head);
// Free the memory
Node *current = head;
Node *next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
return 0;
}
 Edit