Several days ago, I was involved in an argument about choice of C or C++. What I ignored was "language is less important than coder".  a bad C# writer only write shit-like C# but a professional C programmer could design perfect C, Notwithstanding C# is much more powerful than C,
So how to write perfect C code? We just illustrate that by cJson, a famous pure-C tiny json formatter.

1. Power C pointer, make point operation awesome

The string-comparison of cjson like melody,  this ability might need you a lot experience:

 static int cJSON_strcasecmp(const char *s1,const char *s2)
{
if (!s1) return (s1==s2)?0:1;
if (!s2) return 1;
for(; tolower(*s1) == tolower(*s2); ++s1, ++s2)
if(*s1 == 0) return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}

So how you write a same strcasecmp function? Try more C code.

2. Reasonable code indent

Someone might tell you write code with same indent-style, "the wrap position, where to put a bracket..." However, most people are accustomed to reading left to right without pause. So a better code reader understand is more important than that so-call rule and style just like follows:

static const char *parse_value(cJSON *item,const char *value)
{
if (!value) return 0; /* Fail on null. */
if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
if (*value=='\"') { return parse_string(item,value); }
if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
if (*value=='[') { return parse_array(item,value); }
if (*value=='{') { return parse_object(item,value); } ep=value;return 0; /* failure. */
}

Does Code below make it more easy to understand than standard indent style? As you can easily compare difference between each case of switch structure.

3. Chain-style function design

Chain-style function means you can invoke them with merge them into a chain, as A(B(C)).

Linq (a chain-style code sugar ) greatly improve beauty of C#, could
make your code designed like: Select.Where.Orderby...  As standard C do
not offer extend-function. But you could still make the chain like
Order(Select(Where(Data))) .  Some little bit harder ,but much more
easier than other code style, just like code in cJson:

 value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. *

The difficulty is the rope which connect modules into a chain. In
Linq, it's a interface called IEnumerable, a compiler-level state
machine. In cJson code behind, it's the position of processing pointer.

4. Hook me!


Standard C do not have delegate, function override. But there are some
other powerful mechanism called hook, achieved by function pointer. You
could change a function pointer behaviour by assign a different function
with same parameters and return value. Example as follow:

 void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
} cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}

Awesome right? You can change memory allocation and free behaviour by using hook!

5. Offer default value of function parameters

In order to make your user more convenient when using your perfect library, please offer them some override functions! C might not allow you define two same name function by different parameter table. But you could still do this:

/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item) {return print_value(item,0,1);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0);}

6.  Marco and #define

Marco is only way to make C transplant in different platform.

6. Improve algorithm!

C style code is different than C# or Java, the languages with powerful libraries. Sometimes because of compatibility or performance, using STL or some 3rd libraries is not a good choice. So you need to achieved them by yourself. This does not means you should write "Stack.c" or  "Stack.h"  to define a full-functional stack. It's too heavy and unnecessary,right? But the core algorithm of stack will greatly affect your code style by merge an easy array-achieved stack by several simple code.
    The example in cJson is tree structure, as json is a
nature tree. The author merge tree algorithm into the code by recursive
and pointer without any trace. Perfect!
    
    Try more C code, try more perfect improvement, guy!

How to write perfect C code More articles about

  1. java Code formatting

    Java source formatting You are probably familiar with the Eclipse hotkeys to automatically format yo ...

  2. Project Perfect Give Way Swift stay server Run at the end -Perfect in Visual Studio Code ( Four )

    Editor's language : This series of articles has been Perfect Officially quoted , It's a great feeling . Gratitude !Thx all ! Visual Studio Code It's a lightweight editor , But it's also functional , Through the plug-in, you can complete such as Cordo ...

  3. Peer Code Reviews Made Easy with Eclipse Plug-In

    Welcome to my social account : Blog Garden address : http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub Address : https://github.com/ji ...

  4. Perfect smooth scrolling in UITableViews

    https://medium.com/ios-os-x-development/perfect-smooth-scrolling-in-uitableviews-fd609d5275a5 Diffic ...

  5. Unit Testing PowerShell Code with Pester

    Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerS ...

  6. Code Complete Reading notes ( Two )

    2015-03-06   328   Unusual Data Types    ——You can carry this technique to extremes,putting all the ...

  7. Your Job Is Not to Write Code

    I am lucky enough to work with a small team of fantastic engineers who truly care about their custom ...

  8. ResolveUrl in ASP.NET - The Perfect Solution

    original text :ResolveUrl in ASP.NET - The Perfect Solution If you are looking for ResolveUrl outside of Page/Co ...

  9. How to be in python Script development does code review

    In software project development , We often mention a word “code review”.code review Chinese translation is code review or review , In short, it means that after coding is completed, other people check the quality of the code by reading it ( Compiling . Can run . Can be read . ...

Random recommendation

  1. express And sendFile

    module.exports = function(req, res, opt) { var applyNo = req.query.applyNo; console.log("applyN ...

  2. 【 turn 】PowerShell introduction ( 8、 ... and ): function 、 Script 、 Scope

    Transferred to :http://www.cnblogs.com/ceachy/archive/2013/02/26/PoweShell_Function_Script_Scope.html What the script represents is Powe ...

  3. zookeeper Learning Series : 3、 ... and 、 utilize zookeeper Do elections and locks

    I just understood before zk You can name it , Configure the service , Now learn how he used it as an election and a lock , Furthermore, we can build master-slave Pattern of Distributed Systems . Why call Zoo?“ Because the distributed system to be coordinated is a zoo ”. ZooKeeper ...

  4. OC There are two singleton implementations in

    OC There are two singleton implementations in Write it at the front I explored it two days ago C++ Single case , I've learned a lot . Come and have a look today OC What's going on with the single example in the . Check out the information , Found in OC There are generally two ways to implement singletons in , One way is to talk to C++ It's very common in the world ...

  5. Safety operation and maintenance :Linux System account and login security ( turn )

    3、 ... and . Delete the system login welcome information Some welcome information or version information of the system , Although it can bring some convenience to the system manager , But this information can sometimes be used by hackers , Be an accomplice in attacking the server , In order to ensure the safety of the system , You can modify or delete some system files , It needs to be repaired ...

  6. 4 It's special ping

    When your network fails or fails to connect , How to find out the fault simply and efficiently ? It just needs one ping command , You can judge TCP/IP Protocol failure …… 1.Ping 127.0.0.1: 127.0.0.1 It's the local loop address , If Ben ...

  7. A task :( Little turtle python Video No 29 speak ) Code collation and summary

    Mission : Will file (record.txt) To segment the data in , And install the following rules to save .  1. The dialogue of the little turtle is saved as boy_*.txt The file of ( Get rid of " Little turtle :")  2. The conversation of small customer service is saved separately ...

  8. LVM ( Logical volume manager )

    The picture is from :https://www.cnblogs.com/linuxprobe/p/5381538.html Reference blog :https://www.cnblogs.com/linuxprobe/p/538 ...

  9. Django change xadmin Backstage English is Chinese

    1. title setting.py file : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' modify : LANGUAGE_CODE = 'zh-Hans' TIME_ZONE ...

  10. in and or The efficiency of

    select * from table where col in (2,3,4,5,6) select * from table where col=2 or col=3 or col=4 or co ...