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的更多相关文章

  1. java代码格式化

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

  2. Project Perfect让Swift在server端跑起来-Perfect in Visual Studio Code (四)

    编者语 : 本系列文章已经被Perfect官方引用了,这样的感觉非常好.感恩!Thx all ! Visual Studio Code是一个轻量级的编辑器,但也功能丰富,通过插件你能够完毕如Cordo ...

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

    欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub地址: 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阅读笔记(二)

    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

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

  9. 如何在python脚本开发做code review

    在软件项目开发中,我们经常提到一个词“code review”.code review中文翻译过来就是代码评审或复查,简而言之就是编码完成后由其他人通过阅读代码来检查代码的质量(可编译.可运行.可读. ...

随机推荐

  1. 一个简便的方法,获取某个页面元素的Xpath值

    今天了解到一个比较方便获取页面元素Xpath的方法,以下是获取步骤. 1:使用chrome浏览器打开百度:http://www.baidu.com 2:点击邮件,检查. 3:定位到某个页面的元素:点击 ...

  2. wex5中的星星评分

    新建一个空白的.w文件,然后在页面上放5个img星星图片 重要的是图片路径不能是绝对路径,要用相对路径,不然js操作的时候会出bug 添加两个label标签(标签随你挑,在这我就用label) 你到时 ...

  3. 浅谈MySql的存储引擎(表类型)

    来源:http://www.cnblogs.com/lina1006/archive/2011/04/29/2032894.html 什么是MySql数据库 通常意义上,数据库也就是数据的集合,具体到 ...

  4. 命令行操作svn和git和git

    前几天在写代码的时候电脑突然坏掉,老大交代的任务没完成,非常痛恨自己用svn或者git保存代码,相信很多程序员遇到过,硬盘坏掉,存在硬盘中的代码丢失,无法找回的问题,svn和git可谓程序员界的福音, ...

  5. 深入理解OAuth2.0协议

    1. 引言 如果你开车去酒店赴宴,你经常会苦于找不到停车位而耽误很多时间.是否有好办法可以避免这个问题呢?有的,听说有一些豪车的车主就不担心这个问题.豪车一般配备两种钥匙:主钥匙和泊车钥匙.当你到酒店 ...

  6. [LeetCode]444. Sequence Reconstruction

    Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. Th ...

  7. 基于Picture Library创建的图片文档库中的上传多个文件功能(upload multiple files)报错怎么解决?

    复现过程 首先,我创建了一个基于Picture Library的图片文档库,名字是 Pic Lib 创建完毕后,我点击它的Upload 下拉菜单,点击Upload Picture按钮 在弹出的对话框中 ...

  8. IOS网络第七天WebView-02WebView和网页的交互2,删除大众点评多余文字,加上蒙版进度

    ************ #import "HMViewController.h" @interface HMViewController () <UIWebViewDele ...

  9. Finger Trees: A Simple General-purpose Data Structure

    http://staff.city.ac.uk/~ross/papers/FingerTree.html Summary We present 2-3 finger trees, a function ...

  10. 跟vczh看实例学编译原理——二:实现Tinymoe的词法分析

    文章中引用的代码均来自https://github.com/vczh/tinymoe.   实现Tinymoe的第一步自然是一个词法分析器.词法分析其所作的事情很简单,就是把一份代码分割成若干个tok ...