How to write perfect C code
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的更多相关文章
- java代码格式化
Java source formatting You are probably familiar with the Eclipse hotkeys to automatically format yo ...
- Project Perfect让Swift在server端跑起来-Perfect in Visual Studio Code (四)
编者语 : 本系列文章已经被Perfect官方引用了,这样的感觉非常好.感恩!Thx all ! Visual Studio Code是一个轻量级的编辑器,但也功能丰富,通过插件你能够完毕如Cordo ...
- Peer Code Reviews Made Easy with Eclipse Plug-In
欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub地址: https://github.com/ji ...
- Perfect smooth scrolling in UITableViews
https://medium.com/ios-os-x-development/perfect-smooth-scrolling-in-uitableviews-fd609d5275a5 Diffic ...
- Unit Testing PowerShell Code with Pester
Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerS ...
- Code Complete阅读笔记(二)
2015-03-06 328 Unusual Data Types ——You can carry this technique to extremes,putting all the ...
- 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 ...
- ResolveUrl in ASP.NET - The Perfect Solution
原文:ResolveUrl in ASP.NET - The Perfect Solution If you are looking for ResolveUrl outside of Page/Co ...
- 如何在python脚本开发做code review
在软件项目开发中,我们经常提到一个词“code review”.code review中文翻译过来就是代码评审或复查,简而言之就是编码完成后由其他人通过阅读代码来检查代码的质量(可编译.可运行.可读. ...
随机推荐
- bootstrap之clearfix
bootstrap之clearfix 在bootstrap辅助类中有那么一类,是这么定义的: 利用clearfix样式清除浮动,但是前提条件是在超小型屏幕上能显示才行(因为其是用visible-xs样 ...
- 初学者-PHP笔记
PHP介绍 PHP 是 "PHP Hypertext Preprocessor" 的首字母缩略词 PHP 是一种被广泛使用的开源脚本语言 PHP 脚本在服务器上执行 PHP 没有成 ...
- Ubuntu中的快捷键
Ubuntu中的许多操作在终端(Terminal)中十分的快捷,记住一些快捷键的操作更得心应手. 在Ubuntu中打开终端的快捷键是Ctrl+Alt+T.其他的一些常用的快捷键如下: 快捷键 功能 T ...
- SQL语句操作数据与一些函数使用的丰富数据库
数据库有多重要,其实不用我说,但该怎么运用好数据库下SQL语句与其它的如“函数”等等,那就需要我们大家多多去练习并总结其中的窍门,或许你的总结没那么好,担只要你的练习足够多,就算那不是窍门,那也将是你 ...
- JQuery的父、子、兄弟节点查找方法
jQuery.parent(expr) //找父元素 jQuery.parents(expr) //找到所有祖先元素,不限于父元素 jQuery.children ...
- Palm是一家英國智能手機公司
據TCL方面介紹,本次收購只涉及品牌,不會涉及員工和其他資產.被收購之後,Palm仍將繼續把總部設於美國加州矽谷,以發揮該區域所獨有的先進技術和人才的優勢. TCL通訊CEO郭愛平表示TCL將把Pal ...
- 拒绝了对对象 'base_config' (数据库 '****',架构 'dbo')的 SELECT 权限
在网上看了很多资料都是空说一谈,都只是说很简单,然后没有说遇到这样的情况具体该怎么做,看到这里都知道是权限问题,其实我们每一个人都知道,又是我觉得我还是要给以后遇到的朋友个解决方法: 这里用到的数据 ...
- 什么情况下才要重写Objective-C中的description方法
特别注意: 千万不要在description方法中同时使用%@和self,同时使用了%@和self,代表要调用self的description方法,因此最终会导致程序陷入死循环,循环调用descrip ...
- Mac读取Andriod屏幕截图
int main(int argc, const char * argv[]) { // insert code here... string str3 = "/Users/Ethan/Do ...
- SQLite vs MySQL vs PostgreSQL:关系型数据库比较
自1970年埃德加·科德提出关系模型之后,关系型数据库便开始出现,经过了40多年的演化,如今的关系型数据库种类繁多,功能强大,使用广泛.面对如此之多的关系型数据库,我们应该如何权衡找出适合自己应用场景 ...