How I write C Code
Alright, I just thought I’d share a document showing my programming style (with C).
This is kind of adapted (to a point) in other languages such as Golang, or Lua.
Coding Style
Functions
An example of how I declare functions:
type
func (
type arg1,
type arg2
)
{
/* Things */
}
Here’s a real example of a function:
bool
isOdd (
int num
)
{
if ((num % 2) != 0)
return true;
return false;
}
Brackets
I put brackets after parenthesis, except for functions.
An example:
if (<value>) {} <-
type
func (
void
)
{} <-
When I have the chance, I will try to exclude the brackets.
Like this:
This:
if (<value>)
func();
Not this:
if (<value>) {
func();
}
But it's okay when it's like this:
if (<value>) {
func1();
func2();
}
Selections
I choose to use as many guard clauses
as possible.
I also choose to use as little else
keywords too.
For example (function def):
type
func (
void
)
{
if (!globalVar)
return <type>;
while (true) {
if (globalVar != 1) {
printf("test");
break;
}
printf("test2");
otherFunc(globalVar);
}
return <type>;
}
Variables
I try to organize variables using structs.
It’s way more effcient and understandable
Plus it allows you to return more than one variable (Go style).
Global Variables
I try not to use these.
I’d rather just use a preprocessor definition.
Which with both, I declare in a header file.
Overall
Overall, this is how I write in C. I find this to be the most effcient way (in my opinion of course).
It’s based on the (but changed in ways) C89 style.
Like this:
type
func (arg1, arg2)
int arg1;
int arg2;
{}
I believe it to be a great looking way to declare functions.
As it’s showing each variable on individual lines. Rather than on one line.
As an example:
/* Bad, just bad */
type func (int arg1, int arg2) {}
/* Good, but bad with today's standards */
type
func (arg1, arg2)
int arg1;
int arg2;
{}
/* Good, and fits too */
type
func (
int arg1,
int arg2
)
{}
I still prefer C89’s style. However it’s not allowed in most modern instances of C.